package org.ezplatform.goa.document.web.rest;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import org.apache.commons.collections.CollectionUtils;
import org.ezplatform.cloud.api.component.attachment.AttachmentUtilsService;
import org.ezplatform.cloud.api.system.org.OrgApiService;
import org.ezplatform.cloud.common.condition.AppAuthCondition;
import org.ezplatform.cloud.common.log.LogService;
import org.ezplatform.core.annotation.AppAuth;
import org.ezplatform.core.common.WebUser;
import org.ezplatform.core.exception.ValidationException;
import org.ezplatform.core.pagination.PropertyFilter;
import org.ezplatform.core.security.SecurityUtils;
import org.ezplatform.core.service.BaseService;
import org.ezplatform.core.web.controller.BaseController;
import org.ezplatform.core.web.util.WebUtils;
import org.ezplatform.core.web.view.OperationResult;
import org.ezplatform.goa.document.cache.GovCacheManager;
import org.ezplatform.goa.document.constant.LogConstant;
import org.ezplatform.goa.document.dao.GovDocAttachmentDao;
import org.ezplatform.goa.document.entity.*;
import org.ezplatform.goa.document.service.*;
import org.ezplatform.goa.document.util.*;
import org.ezplatform.integ.websocket.annotation.WebsocketCode;
import org.ezplatform.integ.websocket.constant.WebsocketConstant;
import org.ezplatform.integ.websocket.util.WebsocketUtils;
import org.ezplatform.office.api.client.oa.approve.ApproveApiService;
import org.ezplatform.office.api.client.oa.message.MessageApiService;
import org.ezplatform.office.api.client.oa.mobilecommon.MobileCommonApiService;
import org.ezplatform.util.*;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Conditional;
import org.springframework.context.annotation.Lazy;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageImpl;
import org.springframework.data.domain.Pageable;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import java.io.UnsupportedEncodingException;
import java.net.URLDecoder;
import java.util.*;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

/**
 * 发文流程controller
 *
 * @author gexiang
 */
@Controller
@RequestMapping(value = "/api/w/goa/document/docSendfile")
@Conditional(AppAuthCondition.class)
@AppAuth(identifier = "goa_document")
public class GovSendFileWebApiController extends BaseController<GovSendFile, String> {
    /**
     * 日志
     */
    private final Logger logger = LoggerFactory.getLogger(GovSendFileWebApiController.class);

	/*@Autowired
	private GovSendFileDao govSendFileDao;*/

    @Autowired
    private GovSendFileNumService govSendFileNumService;

    @Autowired
    private DocSendReserveFilenoService reserveFileNoService;

    @Autowired
    private GovDocAttachmentService attachementService;

    @Autowired
    private GovDocAttachmentService govDocAttachmentService;

    @Autowired
    private GovSendFileService sendFileService;

    @Autowired
    private SignQueryService signQueryService;

    @Autowired
    private GovDocReceiveFileService GovDocReceiveFileService;

    @Autowired
    private OrgApiService orgApiService;

    @Autowired
    private GovSendSaveFileNoService govSendSaveFileNoService;

    @Autowired
    private DocSendReserveFilenoService sendReserveFileNoService;

    @Autowired
    private GovCommonService govCommonService;

    @Autowired
    private LogService logService;

    @Autowired
    private GovDocFileEditionService fileEditionService;

    @Autowired
    private GovDocFileEditionService govDocFileEditionService;

    @Autowired
    private GovBaseSetService govBaseSetService;

    @Autowired
    private CopyFileUtils copyFileUtils;

    @Autowired
    private GovDocAttachmentDao govDocAttachmentDao;
    @Autowired
    private GovDocHandlingService govDocHandlingService;

    @Autowired
    private AttachmentUtilsService attachmentUtilsService;

    @Autowired
    private DownloadFilesService downloadFilesService;

    @Autowired
    private GoaDocSignApproveFileService signApproveFileService;

    @Autowired
    private DocumentUtils documentUtils;

    @Autowired
    private MobileCommonApiService mobileCommonApiService;

    @Autowired
    private MessageApiService messageApiService;

    @Autowired
    private GovCacheManager govCacheManager;

    @Autowired
    private ApproveApiService approveApiService;

    @Autowired
    @Lazy
    private GovRelRecordService govRelRecordService;

    @Autowired
    private GovDocOperateRecordService govDocOperateRecordService;

    @Override
    protected BaseService<GovSendFile, String> getEntityService() {
        return sendFileService;
    }


    /**
     * @param request
     * @param model
     * @param id
     * @return void
     * @throws
     * @Title: prepareModel
     * @Description: 初始化数据
     */
    @ModelAttribute
    public void prepareModel(HttpServletRequest request, Model model,
                             @RequestParam(value = "id", required = false) String id) {
        super.initPrepareModel(request, model, id);
    }

    /**
     * 获取可查看文号列表
     *
     * @param request
     * @param defineId   流程定义id
     * @param processKey 流程定义编码
     * @param fileNoId   文号id
     * @param filenoName 文号名称
     * @param filenoNum  文号编号
     * @param year       年份
     * @name: getFileNoList
     * @return: java.util.Map<java.lang.String, java.lang.Object>
     * @date: 2022/10/19 11:25
     */
    @RequestMapping(value = "/getFileNoList", method = RequestMethod.POST)
    @ResponseBody
    public Map<String, Object> getFileNoList(HttpServletRequest request) {
        Map<String, Object> map = new HashMap<>();
        List<GovSendFileNum> list = new ArrayList<>();
        WebUser user = WebUtils.getCurrentUser();
        String token = user.getJwtToken();
        String corpId = user.getCorpId(), userId = user.getUserId();
        String isAdmin = "no";
        // 流程id
        String defineId = ValidateUtils.filter(StringUtils.null2String(request.getParameter("defineId")));
        // 流程key
        String processKey = ValidateUtils.filter(StringUtils.null2String(request.getParameter("processKey")));
        // 文号id
        String filenoId = ValidateUtils.filter(StringUtils.null2String(request.getParameter("fileNoId")));
        // 文号名称
        String filenoName = ValidateUtils.filter(StringUtils.null2String(request.getParameter("filenoName")));
        // 文号
        String filenoNum_ = ValidateUtils.filter(StringUtils.null2String(request.getParameter("filenoNum")));
        //年份
        String year = ValidateUtils.filter(StringUtils.null2String(request.getParameter("year")));

        if (!DocumentValidateUtil.validateParamsString(defineId, processKey, filenoId, filenoName, year, filenoNum_)) {
            throw new ValidationException("非法参数");
        }

        if (!DocumentValidateUtil.validateParamsLength(filenoName, -1, 100)) {
            throw new ValidationException("非法参数");
        }
        if (!DocumentValidateUtil.validateParamsLength(filenoNum_, -1, 100)) {
            throw new ValidationException("非法参数");
        }
        if (!DocumentValidateUtil.validateParamsLength(processKey, -1, 100)) {
            throw new ValidationException("非法参数");
        }
        if (!DocumentValidateUtil.validateParamsLength(defineId, -1, 100)) {
            throw new ValidationException("非法参数");
        }
        List<String> scopeList = orgApiService.getOrgIdsByUserIds(userId, corpId, "", "2", token);
        scopeList.add(userId);

        //获取群组id
        List<WebUser.Group_> groups = user.getGroups();
        if (groups != null && groups.size() > 0) {
            for (WebUser.Group_ g : groups) {
                scopeList.add(g.getId());
            }
        }
        //获取岗位id
        String stationids = "";
        List<WebUser.Station_> stationlist = user.getStations();
        if (stationlist != null && stationlist.size() > 0) {
            for (WebUser.Station_ s : stationlist) {
                stationids += s.getId() + ",";
            }
        }
        if (stationids.endsWith(",")) {
            stationids = stationids.substring(0, stationids.length() - 1);
        }
        //String stationids = user.getStationIds();
        if (stationids != null && stationids.length() > 0) {
            String[] sIds = stationids.split(",");
            for (String sid : sIds) {
                scopeList.add(sid);
            }
        }

        if (SecurityUtils.isSuperAdmin(user.getUserName())) {
            isAdmin = "admin";
            list = this.govSendFileNumService.getFileNoList(scopeList, corpId, isAdmin, defineId, processKey);
        } else {
            list = this.govSendFileNumService.getFileNoList(scopeList, corpId, isAdmin, defineId, processKey);
        }
        map.put("filenos", list);
        String createdDateY = DateUtils.getYear();
        map.put("createdDateY", createdDateY);
        if (!list.isEmpty()) {
            GovSendFileNum obj = null;
            if (StringUtils.isBlank(filenoId)) {
                obj = list.get(0);
            } else {
                obj = govSendFileNumService.findOne(filenoId);
            }
            //String fileNoStr = obj.getName();
            String fileno_id = obj.getId();
            if (StringUtils.isBlank(year)) {
                year = createdDateY;
            }
            long startNo = obj.getStartNo();
            // 查询文号列表中对应的每个文号中使用到那一号
            String filenoNumStr = this.sendFileService.getNoByFileNo(fileno_id, year, corpId,
                    obj.getStartNo(), obj.getShowName(), obj.getShowYear(), obj.getShowReset());
            String filenoNum = "1";
            if (StringUtils.isNotEmpty(filenoNumStr)) {
                filenoNum = filenoNumStr;
                if (startNo > Long.parseLong(filenoNum)) {
                    filenoNum = String.valueOf(startNo);
                }
            }
            if (!DocumentValidateUtil.validateParamsString(filenoNum)) {
                throw new ValidationException("非法参数");
            }

            if (!"".equals(filenoName)) {
                for (GovSendFileNum dfn : list) {
                    String fileNoName = dfn.getName();
                    if (fileNoName.equals(filenoName)) {
                        obj = dfn;
                        break;
                    }
                }
            }
            map.put("filenoNum", filenoNum);
            map.put("startNo", obj.getStartNo());
            map.put("figures", obj.getFigures());
            map.put("showName", obj.getShowName());
            map.put("showYear", obj.getShowYear());
            map.put("showReset", obj.getShowReset());
        }
        return map;
    }


    /**
     * 联动文号名称获取流水号
     *
     * @param request
     * @param fileNoId 文号id
     * @param whtype   文号类型
     * @param year     年份
     * @name: getFileNoNum
     * @return: java.util.Map<java.lang.String, java.lang.Object>
     * @date: 2022/10/19 11:26
     */
    @RequestMapping(value = "/getFileNoNum", method = RequestMethod.POST)
    @ResponseBody
    public Map<String, Object> getFileNoNum(HttpServletRequest request) {
        WebUser user = WebUtils.getCurrentUser();
        String corpId = user.getCorpId();
        String createdDateY = DateUtils.getYear();
        String fileNoId = StringUtils.null2String(request.getParameter("fileNoId"));
        if(StringUtils.isEmpty(fileNoId) || "null".equals(fileNoId)){
            return new HashMap<>();
        }
        try {
            fileNoId = URLDecoder.decode(fileNoId, "utf-8");
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        }
        //文号类型 1，手动编号，2空闲编号，3，预留文号
        String whtype = request.getParameter("whtype") == null ? "" : request.getParameter("whtype");
        //年份
        String year = request.getParameter("year") == null ? "" : request.getParameter("year");
        if (!DocumentValidateUtil.validateParamsString(fileNoId, whtype, year)) {
            throw new ValidationException("非法参数");
        }

        // 流水号
        String filenoNumStr = "";
        if (StringUtils.isBlank(year)) {
            year = createdDateY;
        }
        Map<String, Object> map = new HashMap<>();
        GovSendFileNum obj = this.govSendFileNumService.findOne(fileNoId);
        if ("1".equals(whtype)) {
            if (StringUtils.isNoneBlank(fileNoId)) {
                // 流水号
                filenoNumStr = this.sendFileService.getNoByFileNo(fileNoId, year, corpId, obj.getStartNo(),
                        obj.getShowName(), obj.getShowYear(), obj.getShowReset());
                String filenoNum = "1";
                long startno = obj.getStartNo();
                //获取该机关代字的最大值
                if (StringUtils.isNotEmpty(filenoNumStr)) {
                    filenoNum = filenoNumStr;
                    if (startno > Long.parseLong(filenoNum)) {
                        filenoNum = String.valueOf(startno);
                    }
                }
                map.put("fileno", filenoNum);
            }
        } else if ("2".equals(whtype)) {
            //根据传入的文号id，得到空闲编号
            List<Integer> kxbhList = govSendFileNumService.getkxbhList(fileNoId, year, corpId, obj.getStartNo());
            map.put("kxbh", kxbhList);
        } else if ("3".equals(whtype)) {
            List ylbh = reserveFileNoService.getReserveFileListByFileNo(fileNoId, year, corpId);
            map.put("ylbh", ylbh);
        }

        map.put("startNo", obj.getStartNo());
        map.put("figures", obj.getFigures());
        map.put("showName", obj.getShowName());
        map.put("showYear", obj.getShowYear());
        map.put("showReset", obj.getShowReset());

        return map;
    }

    /**
     * 判断传入的文号是否已经使用，或者在预留的文号中
     *
     * @param request
     * @param type         类型
     * @param fileNoId     文号id
     * @param useFileNo    当前使用文号
     * @param preFileNoId  前文号id
     * @param preYear      前文号年份
     * @param preFilenoNum 前文号编号
     * @param year         年份
     * @name: compareFileno
     * @return: java.util.Map<java.lang.String, java.lang.Object>
     * @date: 2022/10/19 11:27
     */
    @RequestMapping(value = "/compareFileno", method = RequestMethod.GET)
    @ResponseBody
    public Map<String, Object> compareFileno(HttpServletRequest request) {
        WebUser user = WebUtils.getCurrentUser();
        String corpId = user.getCorpId();
        String createdDateY = DateUtils.getYear();
        // 文号类型
        String type = request.getParameter("type") == null ? "" : request.getParameter("type");
        //文号id
        String fileNoId = request.getParameter("fileNoId") == null ? "" : request.getParameter("fileNoId");
        //当前使用的流水号
        String useFileNo = request.getParameter("useFileNo") == null ? "" : request.getParameter("useFileNo");
        String preFileNoId = request.getParameter("preFileNoId") == null ? "" : request.getParameter("preFileNoId");
        String preYear = request.getParameter("preYear") == null ? "" : request.getParameter("preYear");
        String preFilenoNum = request.getParameter("preFilenoNum") == null ? "" : request.getParameter("preFilenoNum");
        // 流水号
        //年份
        String year = request.getParameter("year") == null ? "" : request.getParameter("year");
        if (StringUtils.isBlank(year)) {
            year = createdDateY;
        }
        //发文字号名称
        String filenoName = StringUtils.null2String(request.getParameter("filenoName"));
        filenoName = URLDecoder.decode(filenoName);
        //判断流水号是否配置为必填权限
        String editFlag = StringUtils.null2String(request.getParameter("editFlag"));
        //当发起流程时保存后再次保存或保存后提交,并且没有修改文号时不判断文号是否重复
        boolean fileNoFlag = Boolean.parseBoolean(StringUtils.null2String(request.getParameter("fileNoFlag")));

        if (!DocumentValidateUtil.validateParamsString(fileNoId, type, year, preFileNoId, preYear, preFilenoNum)) {
            throw new ValidationException("非法参数");
        }

        boolean flag = Boolean.parseBoolean(editFlag);

        Map<String, Object> map = new HashMap<String, Object>();
        map.put("type", "success");
        if (StringUtils.isNoneBlank(fileNoId)) {
            if (StringUtils.equals(fileNoId, preFileNoId) && StringUtils.equals(year, preYear) && StringUtils.equals(useFileNo, preFilenoNum)) {
                return map;
            }
            //GovSendFileNum obj = this.govSendFileNumService.findOne(fileNoId);
            // 流水号“
            //判断当前文号是否已经被占用，或者被预留
            String result = this.sendFileService.checkCurrentFileNo(fileNoId, useFileNo, year, corpId);
            //获取该机关代字的最大值
            if (fileNoFlag) {
                if ("1".equals(result)) {
                    map.put("type", "faild");
                    map.put("message", "填写的发文字号已经被使用，请重新选择");
                } else if ("2".equals(result)) {
                    map.put("type", "faild");
                    map.put("message", "填写的发文字号已经被占用，请重新选择");
                }
                // 判断当前号码是否是未使用的预留编号
                if (!"3".equals(type)) {
                    int num = this.sendFileService.isKeepFileNo(fileNoId, useFileNo, year, corpId);
                    if (num > 0) {
                        map.put("type", "faild");
                        map.put("message", "填写的发文字号已经被占用，请重新选择");
                    }
                }
            }
        } else if (flag && StringUtils.isBlank(filenoName)) {
            map.put("type", "faild");
            map.put("message", "文号不能为空");
        }
        return map;
    }

    /**
     * 增/修改保存表单之后，需要对里面的特殊字段进行处理。
     *
     * @param request
     * @param type                保存类型
     * @param symbolId            统一标识id
     * @param wh                  文号
     * @param jgdz                机关代字
     * @param processName         流程名称
     * @param whYear              年份
     * @param whNum               文号编号
     * @param fileNoId            文号id
     * @param businessKey         公文数据id
     * @param flag                标志
     * @param menuType            菜单类型
     * @param category            公文类型
     * @param formatRecordId      正式公文recordid
     * @param textType            正文类型
     * @param mainTextType        正文文件；诶下
     * @param formatFileId        正式公文文件id
     * @param taskId              任务id
     * @param streamVersionId     版本记录id
     * @param recordId            正文recordid
     * @param contentType         正文类型
     * @param revisionId          清稿件id
     * @param mainTextFileExt     正文附件类型
     * @param rollFlag            是否回退版本
     * @param attachmentList      附件页签数据
     * @param fileSecurityList    附件密级数据
     * @param permissionCode      授权编号
     * @param oldInstanceid       上一个流程实例id
     * @param newInstanceid       现流程实例id
     * @param govTitle            公文标题
     * @param title               标题
     * @param distributeType      分发类型
     * @param isSaveHistory       是否保存历史版本
     * @param sourceFrom          来源
     * @param handleType          处理类
     * @param useSignApproveFlag  是否使用手写签批
     * @param distributeUserId    分发用户记录id
     * @param disRecordId         分发记录id
     * @param signTextApproveFile 正文签批件recordid
     * @name: updateSendFileInfo
     * @return: org.ezplatform.core.web.view.OperationResult
     * @date: 2022/10/19 11:28
     */
    @WebsocketCode({WebsocketConstant.GOADEAL,WebsocketConstant.GOADEALLIST,WebsocketConstant.GOAEFFICIENCYSTATISTICS,WebsocketConstant.GOACHARTSTATISTICS,WebsocketConstant.SYSREMIND})
    @RequestMapping(value = "/updateSendFileInfo", method = RequestMethod.POST)
    @ResponseBody
    public OperationResult updateSendFileInfo(HttpServletRequest request) {
        WebUser user = WebUtils.getCurrentUser();
        String currentJg = user.getInstitutionId();
        String useName = user.getCnName();
        String corpId = user.getCorpId();
        String message = "保存成功";
        //是否只读字段
        String showFields = StringUtils.null2String(request.getParameter("showFields"));
        //是否隐藏字段
        String hiddenFields =  StringUtils.null2String(request.getParameter("hiddenFields"));
        //如果是可编辑的状态，才去处理字段
        String type = ValidateUtils.filter(StringUtils.null2String(request.getParameter("type")));
        String symbolId = ValidateUtils.filter(StringUtils.null2String(request.getParameter("symbolId")));
        String wh = "";
        String jgdz = "";
        String processName = "";
        try {
            wh = request.getParameter("wh") == null || "undefined".equals(request.getParameter("wh")) ? "" : URLDecoder.decode(request.getParameter("wh"), "UTF-8");
            jgdz = request.getParameter("jgdz") == null || "undefined".equals(request.getParameter("jgdz")) ? "" : URLDecoder.decode(request.getParameter("jgdz"), "UTF-8");
            processName = request.getParameter("processName") == null ? "" : URLDecoder.decode(request.getParameter("processName"), "UTF-8");
        } catch (UnsupportedEncodingException e1) {
            e1.printStackTrace();
        }
        String whYear = request.getParameter("whYear") == null ? "" : request.getParameter("whYear");
        whYear = ValidateUtils.filter(whYear);
        String whNum = request.getParameter("whNum") == null || "undefined".equals(request.getParameter("whNum")) ? "" : request.getParameter("whNum");
        whNum = ValidateUtils.filter(whNum);
        String fileNoId = request.getParameter("fileNoId") == null || "undefined".equals(request.getParameter("fileNoId")) ? "" : request.getParameter("fileNoId");
        fileNoId = ValidateUtils.filter(fileNoId);
        String businessKey = ValidateUtils.filter(StringUtils.null2String(request.getParameter("businessKey")));
        String flag = ValidateUtils.filter(request.getParameter("flag"));
        String menuType = ValidateUtils.filter(request.getParameter("menuType"));
        if (!DocumentValidateUtil.validateParamsString(processName, type, symbolId, fileNoId, businessKey, flag, menuType)) {
            throw new ValidationException("非法参数");
        }

        GovSendFile sendFile = sendFileService.findOne(businessKey);
        if (StringUtils.isEmpty(type) && !"undefined".equals(type)) type = sendFile.getFlowStatus();
        //如果是新增，保存草稿
        //保存文号
        try {
            logger.info("保存文号开始的文件id：" + sendFile.getId() + ",标题：" + sendFile.getTitle());
            //文号是可编辑的处理，否则不处理
            if(!((StringUtils.isNotBlank(showFields) && showFields.indexOf("goa_doc_sendfile_issued_number")>-1)
                    || (StringUtils.isNotBlank(hiddenFields) && hiddenFields.indexOf("goa_doc_sendfile_issued_number")>-1))){
                message = saveFileNo(currentJg, useName, corpId, type, symbolId, wh, jgdz, processName, whYear, whNum, fileNoId, sendFile, flag);
            }
            saveSendfileInfo(type, sendFile, flag, symbolId, processName, currentJg);
        } catch (Exception e) {
            logger.error("保存文号错误", e);
        }

        String category = ValidateUtils.filter(StringUtils.null2String(request.getParameter("category")));
        String formatRecordId = ValidateUtils.filter(StringUtils.null2String(request.getParameter("formatRecordId")));
        String textType = ValidateUtils.filter(StringUtils.null2String(request.getParameter("textType")));
        String mainTextType = ValidateUtils.filter(StringUtils.null2String(request.getParameter("mainTextType")));
        String formatFileId = ValidateUtils.filter(StringUtils.null2String(request.getParameter("formatFileId")));
        String taskId = ValidateUtils.filter(StringUtils.null2String(request.getParameter("taskId")));
        String streamVersionId = request.getParameter("streamVersionId");

        String recordId = ValidateUtils.filter(StringUtils.null2String(request.getParameter("recordId")));
        String contentType = ValidateUtils.filter(StringUtils.null2String(request.getParameter("contentType")));
        String revisionId = ValidateUtils.filter(StringUtils.null2String(request.getParameter("revisionId")));
        String mainTextFileExt = ValidateUtils.filter(StringUtils.null2String(request.getParameter("mainTextFileExt")));
        String rollFlag = ValidateUtils.filter(StringUtils.null2String(request.getParameter("rollFlag")));

        String attachmentList = request.getParameter("attachmentList");
        String initAttachmentList = request.getParameter("initAttachmentList");
        String fileSecurityList = request.getParameter("fileSecurityList");
        String permissionCode = ValidateUtils.filter(request.getParameter("permissionCode"));

        String oldInstanceid = ValidateUtils.filter(request.getParameter("oldInstanceid"));
        String newInstanceid = ValidateUtils.filter(request.getParameter("newInstanceid"));
        String govTitle = request.getParameter("govTitle");
        String title = request.getParameter("title");
        String distributeType = ValidateUtils.filter(request.getParameter("distributeType"));
        String isSaveHistory = ValidateUtils.filter(request.getParameter("isSaveHistory"));
        String sourceFrom = ValidateUtils.filter(request.getParameter("sourceFrom"));
        String handleType = ValidateUtils.filter(request.getParameter("handleType"));
        String signTextApproveFormatFile = request.getParameter("signTextApproveFormatFile");
        String useSignApproveFlag = ValidateUtils.filter(request.getParameter("useSignApproveFlag"));
        //是否核稿 0-否 1-是
        String reviewSignApprove = ValidateUtils.filter(request.getParameter("reviewSignApprove"));
        //是否多文件签批 0-否 1-是
        String multipleSignApprove = ValidateUtils.filter(request.getParameter("multipleSignApprove"));
        //正式文件签批类型 0 同文件  1 多文件
        String formatMultipleSignApprove = StringUtils.null2String(request.getParameter("formatMultipleSignApprove"));
        //正文签批模板文件id
        String signApproveTempId = ValidateUtils.filter(request.getParameter("signApproveTempId"));
        //正式公文签批模板文件id
        String signApproveFormatTempId = ValidateUtils.filter(request.getParameter("signApproveFormatTempId"));
        //签批内容 0 表单 1 正文 2 表单&正文
        String handSignatureContent = request.getParameter("handSignatureContent");
        //是否可以手写签批 0 不可以 1 可以
        String canHandSignature = request.getParameter("canHandSignature");
        //获取正文和正式公文是否进行分转章和擦除操作
        String signChangeObjStr = StringUtils.null2String(request.getParameter("signChangeObjStr"));
        //是否开启手写签批 0-否 1-是
        String enableHandSignature = StringUtils.null2String(request.getParameter("enableHandSignature"));
        //加盖分转章 1是 0否
        //String stampedTransferSeal = ValidateUtils.filter(request.getParameter("stampedTransferSeal"));
        String stampedTransferSeal = "0";//重新赋予变量的新含义（2-代表盖了分转章或者进行签批擦除操作），以前的1-代表只要有分转章按钮（1表示的状态现在作废不用了）
        String parentProcessInstanceId = request.getParameter("parentProcessInstanceId");

        if (StringUtils.isNotEmpty(fileSecurityList)) {
            JSONObject fileSecurityJson = JSONObject.parseObject(fileSecurityList);
            Iterator iter = fileSecurityJson.entrySet().iterator();
            while (iter.hasNext()) {
                Map.Entry entry = (Map.Entry) iter.next();
                if (!DocumentValidateUtil.validateParamsString(StringUtils.null2String(entry.getKey()), StringUtils.null2String(entry.getValue()))) {
                    throw new ValidationException("非法参数");
                }
            }
        }

        if (!DocumentValidateUtil.validateParamsString(category, formatRecordId, textType, mainTextType, formatFileId, taskId, streamVersionId, recordId, contentType,
                revisionId, mainTextFileExt, rollFlag, attachmentList, permissionCode, oldInstanceid, newInstanceid, distributeType,
                isSaveHistory, sourceFrom, handleType, useSignApproveFlag)) {
            throw new ValidationException("非法参数");
        }

        if (!DocumentValidateUtil.validateTitle(title)) {
            throw new ValidationException("非法参数");
        }
        if (!DocumentValidateUtil.validateTitle(govTitle)) {
            throw new ValidationException("非法参数");
        }

        if (StringUtils.isEmpty(distributeType)) {
            distributeType = "0"; // 0代表是草稿状态进行转的操作
        }

        if(StringUtils.isEmpty(stampedTransferSeal)){
            stampedTransferSeal = "0";
        }
        String distributeUserId = ValidateUtils.filter(request.getParameter("distributeUserId"));

        String disRecordId = ValidateUtils.filter(request.getParameter("disRecordId"));
        String signTextApproveFile = ValidateUtils.filter(request.getParameter("signTextApproveFile"));

        if (!DocumentValidateUtil.validateParamsString(distributeUserId, disRecordId, signTextApproveFile)) {
            throw new ValidationException("非法参数");
        }

        if ("1".equals(flag) || "0".equals(flag) || "3".equals(flag) || "6".equals(flag) || "2".equals(flag) || "5".equals(flag)) {
            // 注释代码：保存正式公文版式记录统一走GovFlowOptButtonWebApiController.saveFormatHistory接口
//            try {
//                //保存版式记录
//                saveFormatHistory(user, businessKey, sendFile, formatRecordId, textType, formatFileId, taskId, streamVersionId);
//            } catch (Exception e) {
//                logger.error("保存版式记录错误", e);
//            }
            //保存拟稿单位
            if ("0".equals(flag) || "1".equals(flag)) {
                String createdOrg = sendFile.getCreatedOrg();
                if (StringUtils.isNotBlank(createdOrg)) {
                    String draftUnitName = govBaseSetService.getUnitLongByOrgId(createdOrg);
                    sendFile.setDraftUnitName(draftUnitName);
                }
            }

            try {
                Map<String,String> recordOfdMap = new HashMap<>();
                recordOfdMap.put("dataId",businessKey);
                recordOfdMap.put("userId",user.getUserId());
                recordOfdMap.put("userName",user.getCnName());
                recordOfdMap.put("orgId",user.getOrgId());
                recordOfdMap.put("orgName",user.getOrgName());
                recordOfdMap.put("processInstanceId",newInstanceid);
                recordOfdMap.put("taskId",taskId);
                recordOfdMap.put("taskName",fileEditionService.getTaskName(taskId));
                recordOfdMap.put("moduleCode","goa_document");
                recordOfdMap.put("processName",processName);
                recordOfdMap.put("isStart","1".equals(flag)?"1":"0");
                recordOfdMap.put("parentProcessInstanceId",parentProcessInstanceId);
                //recordOfdMap.put("type","2");
                //recordOfdMap.put("status","0");//0-失败，1-成功
                recordOfdMap.put("startSendSubProcess","");
                recordOfdMap.put("canHandSignature",canHandSignature);
                recordOfdMap.put("isInHandSignScope","");
                recordOfdMap.put("fileName",sendFile.getTitle());
                recordOfdMap.put("fileType","ofd");
                recordOfdMap.put("multipleSignApprove",multipleSignApprove);
                recordOfdMap.put("attachmentIds","");
                recordOfdMap.put("corpId",user.getCorpId());
                recordOfdMap.put("categoryCode","goa_doc_receivefile");
                recordOfdMap.put("preRecordId","");
                recordOfdMap.put("ofdAttId","");
                recordOfdMap.put("isSeal","");
                //保存正文
                saveMainText(user, businessKey, sendFile, formatRecordId, mainTextType, recordId, contentType,
                        revisionId, mainTextFileExt, signTextApproveFile, signTextApproveFormatFile,useSignApproveFlag,
                        multipleSignApprove,formatMultipleSignApprove,recordOfdMap,signApproveTempId,signApproveFormatTempId);
            } catch (Exception e) {
                logger.error("保存正文错误", e);
            }
            if ("1".equals(isSaveHistory) && ("pending".equals(menuType) || "1".equals(rollFlag))) {
                try {
                    //保存正文版本
//					sendFileService.saveTextHistory(user, businessKey, taskId, recordId, rollFlag);
                } catch (Exception e) {
                    logger.error("保存正文版本错误", e);
                }
            }
        }
        if ("7".equals(flag)) {
            try {
                saveMainText(user, businessKey, sendFile, "", "", "", "", "", "",
                        signTextApproveFile, signTextApproveFormatFile,useSignApproveFlag,multipleSignApprove,formatMultipleSignApprove,new HashMap<>(),"","");
            } catch (Exception e) {
                logger.error("保存正文签批错误", e);
            }
        }
        JSONObject signChangeObj = null;
        String streamChangeWhz = "";
        String streamChangeErase = "";
        String formatChangeWhz = "";
        String formatChangeErase = "";
        if(StringUtils.isNotBlank(signChangeObjStr)){
            //查询保存按钮时，有没有进行擦除和盖分转章
            Map recordMap = govDocOperateRecordService.getOperateRecordInfo(businessKey, newInstanceid, taskId, user.getUserId());
            String operateContent = StringUtils.null2String(recordMap.get("operateContent"));
            JSONObject operateContentObj = null;
            if(StringUtils.isNotBlank(operateContent)){
                signChangeObjStr = operateContent;
            }
            signChangeObj = JSON.parseObject(signChangeObjStr);
            streamChangeWhz = "true".equals(streamChangeWhz)?streamChangeWhz:signChangeObj.getString("streamChangeWhz");
            streamChangeErase = "true".equals(streamChangeErase)?streamChangeErase:signChangeObj.getString("streamChangeErase");
            formatChangeWhz = "true".equals(formatChangeWhz)?formatChangeWhz:signChangeObj.getString("formatChangeWhz");
            formatChangeErase = "true".equals(formatChangeErase)?formatChangeErase:signChangeObj.getString("formatChangeErase");
            logger.info("=============signChangeObj:{}==",signChangeObj);
        }

        //目前"6".equals(type)代表：重新发起保存操作
        if (!"6".equals(type) && "pending".equals(menuType) && ("0,1,2,7").indexOf(flag)==-1  && ("1".equals(canHandSignature) &&
                (handSignatureContent.indexOf("1") != -1 || handSignatureContent.indexOf("2") != -1) ||(signChangeObj!=null&&signChangeObj.size()>0))) {
            try {
                //判断是否在签批范围内
                String containsFlag = "1";//0-否，1-是
                List<String> userIdList = govRelRecordService.getUserIdList(newInstanceid,taskId);
                if(userIdList!=null&&userIdList.size()>0){
                    if(userIdList.contains(user.getUserId())){
                        containsFlag = "1";
                    }else{
                        containsFlag = "0";
                    }
                }

                String displayName = "";
                String displayName2 = "";
                //保存正文签批版本
                if("0".equals(multipleSignApprove)){
                    displayName = title+"(正文签批单)";
                }else if("1".equals(multipleSignApprove)){
                    displayName = title+"(正文签批单)"+"_"+user.getCnName();
                }
                logger.info("===========保存正文签批最新记录===="+sendFile.getSignApproveId());
                if("1".equals(canHandSignature) || "true".equals(streamChangeWhz)||"true".equals(streamChangeErase)){
                    //logger.error("===========保存正式公文签批最新记录===saveTextApproveHistory111="+canHandSignature);
                    if(!("1".equals(canHandSignature)&&"1".equals(containsFlag)) && ("true".equals(streamChangeWhz)||"true".equals(streamChangeErase))){
                        stampedTransferSeal = "2";//重新赋予变量的新含义（2-代表盖了分转章或者进行签批擦除操作）
                    }else{
                        stampedTransferSeal = "0";
                    }
                    if("1".equals(canHandSignature)&&"1".equals(containsFlag)||"2".equals(stampedTransferSeal)){
                        sendFileService.saveTextApproveHistory(user, businessKey, taskId, sendFile.getSignApproveId(), multipleSignApprove, flag,displayName,"3", parentProcessInstanceId, newInstanceid, processName,stampedTransferSeal);
                    }
                }
                //保存正式公文签批版本
                if("0".equals(formatMultipleSignApprove)){
                    displayName2 = title+"(正式公文签批单)";
                }else if("1".equals(formatMultipleSignApprove)){
                    displayName2 = title+"(正式公文签批单)"+"_"+user.getCnName();
                }
                //logger.error("===========保存正式公文签批最新记录===="+sendFile.getSignApproveFormatId());
                if("1".equals(canHandSignature) || "true".equals(formatChangeWhz)||"true".equals(formatChangeErase)){
                    if(!("1".equals(canHandSignature)&&"1".equals(containsFlag)) && ("true".equals(formatChangeWhz)||"true".equals(formatChangeErase))){
                        stampedTransferSeal = "2";//重新赋予变量的新含义（2-代表盖了分转章或者进行签批擦除操作）
                    }else{
                        stampedTransferSeal = "0";
                    }
                    if("1".equals(canHandSignature)&&"1".equals(containsFlag)||"2".equals(stampedTransferSeal)){
                        sendFileService.saveTextApproveHistory(user, businessKey, taskId, sendFile.getSignApproveFormatId(), formatMultipleSignApprove, flag,displayName,"4", parentProcessInstanceId, newInstanceid, processName,stampedTransferSeal);
                    }
                }
            } catch (Exception e) {
                logger.error("保存正文签批错误", e);
            }
        }
        if(StringUtils.isNotBlank(signApproveTempId) && "1".equals(multipleSignApprove)){
            //保存签批版式文件模板(与正文版本对应)
            List<GovDocFileEdition> fileEditionList = fileEditionService.getListByGoaId(businessKey, "1");
            if(CollectionUtils.isNotEmpty(fileEditionList)){
                GovDocFileEdition fileEdition = fileEditionList.get(0);
                signApproveFileService.saveSignApproveTemp(fileEdition,signApproveTempId);
                sendFile.setSignApproveId(signApproveTempId);
                sendFileService.save(sendFile);
            }
        }

        if (StringUtils.isNotBlank(signApproveFormatTempId) && "1".equals(formatMultipleSignApprove)) {
            //保存签批版式文件模板(与正式公文版本对应) 查询正式公文是否有变动
            List<GovDocFileEdition> fileEditionList = fileEditionService.getListByGoaId(businessKey, "2");
            if (CollectionUtils.isNotEmpty(fileEditionList)) {
                GovDocFileEdition fileEdition = fileEditionList.get(0);
                signApproveFileService.saveSignApproveFormatTemp(fileEdition, signApproveFormatTempId);
                sendFile.setSignApproveFormatId(signApproveFormatTempId);
                sendFileService.save(sendFile);
            }
        }

        //修改是否核稿状态
        if("6".equals(flag) && "1".equals(multipleSignApprove) && "1".equals(reviewSignApprove)){
            signApproveFileService.updateIsReview(businessKey);
        }
        if("6".equals(flag) && "1".equals(formatMultipleSignApprove) && "1".equals(reviewSignApprove)){
            signApproveFileService.updateIsReviewFormat(businessKey);
        }

        if("1".equals(useSignApproveFlag)){
            //清除会签人员记录缓存
            govCacheManager.removeGovTextSignRecordInfoCache(businessKey);
        }
        try {
            //更新附件表主表id
            sendFileService.updateAttachmentDocumentId(type, businessKey, attachmentList,initAttachmentList, fileSecurityList, permissionCode,enableHandSignature,taskId,title);
        } catch (Exception e) {
            logger.error("更新附件表主表id", e);
        }

        if ("1".equals(flag) || "0".equals(flag) || "6".equals(flag) || "3".equals(flag) || "4".equals(flag)) {
            if (("start".equals(menuType) && "translationButton".equals(sourceFrom)) || ("draft".equals(menuType) && "translationButton".equals(sourceFrom))) {
                try {
                    //转文记录相关公文
                    sendFileService.saveDocHandling(user, handleType, businessKey, flag, oldInstanceid, newInstanceid, title, distributeType, distributeUserId, disRecordId, menuType);
                } catch (Exception e) {
                    logger.error("转文记录相关公文", e);
                }
            }
        }
        WebsocketUtils.setReceiverById(null);
        return OperationResult.buildSuccessResult(message);
    }

    /**
     * @param user
     * @param businessKey
     * @param sendFile
     * @param formatRecordId
     * @param textType
     * @param recordId
     * @param contentType
     * @param revisionId
     * @param mainTextFileExt
     * @name: saveMainText
     * @description: 保存正文
     * @return: void
     * @date: 2021/5/25 16:11
     * @auther: fsx
     */
    private void saveMainText(WebUser user, String businessKey, GovSendFile sendFile, String formatRecordId,
                              String textType, String recordId, String contentType, String revisionId, String mainTextFileExt,
                              String signTextApproveFile, String signTextApproveFormatFile,
                              String useSignApproveFlag, String multipleSignApprove, String formatMultipleSignApprove,
                              Map<String,String> recordOfdMap,String signApproveTempId,String signApproveFormatTempId ) {
        if (sendFile != null) {
            //判断如果正文的id已经存在，并且在流程已经运行中了。则不能值为空
            logger.info("更新发文正文数据：主键id为："+sendFile.getId());
            logger.info("更新发文正文数据，前端recordId为："+recordId+",formatRecordId:"+formatRecordId+",revisionId："+revisionId);
            if (StringUtils.isNotBlank(recordId) && !"null".equals(recordId) ) {
                sendFile.setFileContent(recordId);
            }
            if (StringUtils.isNotBlank(formatRecordId)  && !"null".equals(formatRecordId) ) {
                sendFile.setFormatFile(formatRecordId);
            }
            if (StringUtils.isNotBlank(contentType) && !"null".equals(contentType) ) {
                sendFile.setContentType(contentType);
            }
            if (StringUtils.isNotBlank(revisionId) && !"null".equals(revisionId) ) {
                sendFile.setRevisionFile(revisionId);
            }
            if (StringUtils.isNotBlank(textType) && !"null".equals(textType) ) {
                sendFile.setMainTextClient(textType);
            }
            if (StringUtils.isNotBlank(mainTextFileExt) && !"null".equals(mainTextFileExt) ) {
                sendFile.setMainTextFileExt(mainTextFileExt);
            }
            if (StringUtils.isNotBlank(signTextApproveFile) && !"null".equals(signTextApproveFile) ) {
                sendFile.setSignApproveId(signTextApproveFile);
            }
            if (StringUtils.isNotBlank(signTextApproveFormatFile)) {
                sendFile.setSignApproveFormatId(signTextApproveFormatFile);
            }

            if ( "1".equals(useSignApproveFlag)) {
                String token = user.getJwtToken();
                String corpId = user.getCorpId();
                String formatwritten = documentUtils.getSysParamValueByMark(corpId, token, "formatwritten");
                //生成文件类型
                String fileType = "ofd";
                if ("goldgrid".equals(formatwritten)) {
                    fileType = "pdf";
                }
                //生成正文签批版式文件(同文件签批)
                String moduleCode = "goa_document";
                if("0".equals(multipleSignApprove)) {
                    recordOfdMap.put("multipleSignApprove","0");
                    recordOfdMap.put("type","1");
                    logger.info("===发文===FileContent===");
                    String signApproveId = signApproveFileService.getFileContentQianPi(sendFile.getFileContent(), sendFile.getSignApproveId(), moduleCode, sendFile.getTitle());
                    recordOfdMap.put("preRecordId",sendFile.getFileContent());
                    if (StringUtils.isNotBlank(signApproveId)) {
                        sendFile.setSignApproveId(signApproveId);
                        recordOfdMap.put("ofdAttId",signApproveId);
                        recordOfdMap.put("status","1");
                    }else{
                        recordOfdMap.put("status","0");

                    }
                    logger.info("===发文===FileContent===recordOfdMap:{}===",recordOfdMap);
                    if(StringUtils.isNotBlank(sendFile.getFileContent()) && StringUtils.isNotEmpty(StringUtils.null2String(recordOfdMap.get("fileName")))){
                        try {
                            approveApiService.saveRecordOfd(recordOfdMap,this.TOKEN);
                        } catch (Exception e){
                            logger.info("===发文===saveRecordOfd===", e);
                            e.printStackTrace();
                        }
                    }
                    logger.info("===发文===FileContent===saveRecordOfd==end==");
                }
                //生成正式文件签批版式文件(同文件签批)
                if("0".equals(formatMultipleSignApprove)) {
                    recordOfdMap.put("multipleSignApprove","0");
                    recordOfdMap.put("type","2");
                    recordOfdMap.put("preRecordId",sendFile.getFormatFile());
                    String signApproveFormatId = signApproveFileService.getFormatFileQianPi(sendFile.getFormatFile(), sendFile.getSignApproveFormatId(), moduleCode, sendFile.getTitle());
                    if (StringUtils.isNotBlank(signApproveFormatId)) {
                        sendFile.setSignApproveFormatId(signApproveFormatId);
                        recordOfdMap.put("ofdAttId",signApproveFormatId);
                        recordOfdMap.put("status","1");
                    }else{
                        recordOfdMap.put("status","0");
                    }
                    if(StringUtils.isNotBlank(sendFile.getFormatFile()) && StringUtils.isNotEmpty(StringUtils.null2String(recordOfdMap.get("fileName")))){
                        try {
                            approveApiService.saveRecordOfd(recordOfdMap,this.TOKEN);
                        } catch (Exception e){
                            e.printStackTrace();
                        }
                    }

                }
                if("1".equals(multipleSignApprove)){
                    recordOfdMap.put("multipleSignApprove","1");
                    recordOfdMap.put("type","1");
                    recordOfdMap.put("preRecordId",sendFile.getFileContent());
                    if (StringUtils.isNotBlank(signApproveTempId)) {
                        recordOfdMap.put("ofdAttId",signApproveTempId);
                        recordOfdMap.put("status","1");
                    }else {
                        recordOfdMap.put("status","0");
                    }
                    if(StringUtils.isNotBlank(sendFile.getFileContent()) &&  StringUtils.isNotEmpty(StringUtils.null2String(recordOfdMap.get("fileName")))){
                        try {
                            approveApiService.saveRecordOfd(recordOfdMap,this.TOKEN);
                        } catch (Exception e){
                            e.printStackTrace();
                        }
                    }
                }
                if("1".equals(formatMultipleSignApprove)){
                    recordOfdMap.put("multipleSignApprove","1");
                    recordOfdMap.put("type","2");
                    recordOfdMap.put("preRecordId",sendFile.getFormatFile());
                    if (StringUtils.isNotBlank(signApproveFormatTempId)) {
                        recordOfdMap.put("ofdAttId",signApproveFormatTempId);
                        recordOfdMap.put("status","1");
                    }else {
                        recordOfdMap.put("status","0");
                    }
                    if(StringUtils.isNotBlank(sendFile.getFormatFile()) &&  StringUtils.isNotEmpty(StringUtils.null2String(recordOfdMap.get("fileName")))){
                        try {
                            approveApiService.saveRecordOfd(recordOfdMap,this.TOKEN);
                        } catch (Exception e){
                            e.printStackTrace();
                        }
                    }
                }
            }
            sendFileService.save(sendFile);
        }
        // 版式
        // 处理版本记录
        List<GovDocFileEdition> savedoclist = new ArrayList<GovDocFileEdition>();
        List<GovDocFileEdition> listformat = fileEditionService.getListByGoaId(businessKey, "2");
        List<GovDocFileEdition> listformat1 = fileEditionService.getListByGoaId(businessKey, "1");
        GovDocFileEdition gformat = new GovDocFileEdition();
        if (CollectionUtils.isNotEmpty(listformat1)) {
            gformat = listformat1.get(0);
        }
        if (CollectionUtils.isEmpty(listformat) && StringUtils.isNotBlank(formatRecordId) && StringUtils.isNotBlank(recordId)) {
            String newFileId = "";
            String checksum = "";
            Map<String,Object> formatFileInfo = attachementService.getFormatFileInfo(formatRecordId);
            String file_id = formatFileInfo.get("id")==null?"":formatFileInfo.get("id").toString();
            Map newAttachment = copyFileUtils.copyFileByAttachId(file_id, null);
            if (newAttachment != null) {
                newFileId = newAttachment.get("id").toString();
                checksum = newAttachment.get("checksum").toString();
            }
            Integer version = 0;
            GovDocFileEdition g = new GovDocFileEdition();
            // 公文id
            g.setGoaId(businessKey);
            // 版本号
            g.setTextVersion(1);
            // 生成版本人员
            g.setVersionName(user.getUserId());
            // 生成版本时间
            g.setVersionTime(new Date());
            // 生成版本部门
            g.setVersionUnit(user.getOrgId());
            // 文件类型：1：正文版本，2：正式公文版本。
            g.setFileType("2");
            // 历史版本附件id
            g.setFileId(newFileId);
            // 正文版本
            g.setStreamVersion("V1");
            // 公文的recordId
            g.setRecordId(formatRecordId);
            // 版本号名称
            g.setTextVersionName("V1");
            // 附件checksum
            g.setChecksum( checksum);
            // taskId
            g.setTaskId(gformat.getTaskId());
            if (StringUtils.isNotEmpty(gformat.getTaskId())) {
                g.setTaskName(fileEditionService.getTaskName(gformat.getTaskId()));
            }
            // 转版式文件要记录被专版的正文的版本
            g.setStreamVersion("V1");
            //是否隐藏:0-否;1是
            g.setIsHidden("0");
            //是否核稿:0-否;1是
            g.setIsReview("0");
            savedoclist.add(g);
        }
        if (CollectionUtils.isNotEmpty(savedoclist) && savedoclist.size()>0) {
            fileEditionService.save(savedoclist);
        }
    }

    /**
     * @param user
     * @param businessKey
     * @param sendfile
     * @param formatRecordId
     * @param textType
     * @param formatFileId
     * @param taskId
     * @param streamVersionId
     * @name: saveFormatHistory
     * @description: 保存版式历史记录
     * @return: void
     * @date: 2021/5/25 16:11
     * @auther: fsx
     */
    private void saveFormatHistory(WebUser user, String businessKey, GovSendFile sendfile, String formatRecordId,
                                   String textType, String formatFileId, String taskId, String streamVersionId) {
        if (StringUtils.isNotEmpty(formatRecordId) && StringUtils.isNotEmpty(textType)) {
            if (!textType.startsWith(".")) {
                textType = "." + textType;
            }
            Boolean versionFlag = false;
            if (StringUtils.isEmpty(formatFileId)) {
                //获取该版式的fileid
                String fileName = formatRecordId + textType;
                Map<String, String> attachmentFile = attachmentUtilsService.getAttachmentByFileName(fileName, WebUtils.getCurrentUser().getJwtToken());
                if (attachmentFile != null) {
                    String fileId = attachmentFile.get("id").toString();
                    formatFileId = fileId;
                    versionFlag = true;
                } else {
                    versionFlag = false;
                }
            }
            if (StringUtils.isNotEmpty(sendfile.getFormatFile())) {
                if (!sendfile.getFormatFile().equals(formatRecordId)) {
                    versionFlag = true;
                }
            } else {
                versionFlag = true;
            }
            //版本记录表
            //获取之前最新版本
            if (versionFlag) {
                //产生新的fileid
                String newFileId = "";
                Map newAttachment = copyFileUtils.copyFileByAttachId(formatFileId, null);
                if (newAttachment != null) {
                    newFileId = newAttachment.get("id").toString();
                }
                Integer version = 0;
                GovDocFileEdition edition = null;
                List<Map> versionList = this.fileEditionService.getEditions(businessKey, "2");
                if (versionList != null && versionList.size() > 0) {
                    Map maxone = versionList.get(0);
                    version = maxone.get("textVersion") == null ? 0 : Integer.parseInt(maxone.get("textVersion").toString());
                    String createdBy = maxone.get("createdBy").toString();
                    String maxtaskId = maxone.get("task_id").toString();
                    if (createdBy.equals(user.getUserId()) && maxtaskId.equals(taskId)) {//当前环节同一个人已经生成一个版本(不会在生成新的版本)
                        String editionId = maxone.get("id").toString();
                        edition = fileEditionService.findOne(editionId);
                    }
                }
                String streamVersion = "";
                if (StringUtils.isNotEmpty(streamVersionId)) {
                    streamVersion = "V" + streamVersionId;
                } else {
                    List<Map> streamList = this.fileEditionService.getEditions(businessKey, "1");
                    if (streamList != null && !streamList.isEmpty()) {
                        streamVersion = "V1";
                    }
                }
                if (edition == null) {
                    edition = new GovDocFileEdition();
                    edition.setTextVersionName("V" + (version + 1));
                    edition.setTextVersion(version + 1);
                }
                edition.setFileType("2");//正式公文类型
                edition.setGoaId(businessKey);
                edition.setTaskId(taskId);
                if (StringUtils.isNotEmpty(taskId)) {
                    edition.setTaskName(fileEditionService.getTaskName(taskId));
                }
                edition.setStreamVersion(streamVersion);
                edition.setRecordId(formatRecordId);
                edition.setVersionName(user.getUserId());
                edition.setVersionTime(new Date());
                edition.setVersionUnit(user.getOrgId());
                edition.setFileId(newFileId);
                //是否隐藏:0-否;1是
                edition.setIsHidden("0");
                //是否核稿:0-否;1是
                edition.setIsReview("0");
                this.fileEditionService.save(edition);
            }
        }
    }

    /**
     * @param currentJg
     * @param useName
     * @param corpId
     * @param type
     * @param symbolId
     * @param wh
     * @param jgdz
     * @param processName
     * @param whYear
     * @param whNum
     * @param fileNoId
     * @param sendfile
     * @name: saveFileNo
     * @description: 保存文号
     * @return: void
     * @date: 2021/5/25 15:52
     * @auther: fsx
     */
    private String saveFileNo(String currentJg, String useName, String corpId, String type, String symbolId,
                              String wh, String jgdz, String processName, String whYear, String whNum, String fileNoId, GovSendFile sendfile, String flag) {
        Boolean isUsed = false;
        String issuedNum = sendfile.getIssuedNumber();
        String file_no_see = sendfile.getFileNoSee();
        logger.error("保存文号开始issuedNum:"+issuedNum);
        logger.error("保存文号开始wh:"+wh);
        logger.error("保存文号开始file_no_see:"+file_no_see);
        logger.error("dataid:"+sendfile.getId());
        logger.error("fileNoId:"+fileNoId);
        if (StringUtils.isNotEmpty(wh) && StringUtils.isEmpty(issuedNum)) {
            issuedNum = sendFileService.convertDocumentNumber(wh);//将文号转换
            if (StringUtils.isNotEmpty(issuedNum)) {
                sendfile.setIssuedNumber(issuedNum);
                sendfile.setFileNoSee(wh);
            }
            logger.info("错误====issuedNum：" + issuedNum);
        }
        if (StringUtils.isNotEmpty(issuedNum)) {
            //出现一种情况，前台接收wh是空的。但是数据库是有值的，先用file_no_see 去赋值，否则需要再次进行转换,
            if(StringUtils.isEmpty(wh)){
                logger.info("wh为空，数据库有值"+wh+",issuedNum:"+issuedNum);
                if(StringUtils.isNotEmpty(file_no_see) && StringUtils.isEmpty(wh)){
                    wh = file_no_see;
                }else{
                    wh = sendFileService.convertIssuedNumerToWh(issuedNum);
                }
            }
            //出现一种情况，wh有值issuedNum有值，但是fileno没有值，从wh去反推filenoId
            if(StringUtils.isEmpty(fileNoId) ){
                fileNoId = sendFileService.getFileNoIdByWh(issuedNum);
            }
        }
        logger.error("type的值:"+type);
        if (("1".equals(type) || "0".equals(type) || ("3".equals(type) && !"4".equals(flag)) || "2".equals(type) || "6".equals(type)) && StringUtils.isNotEmpty(wh) && StringUtils.isNotEmpty(issuedNum)) {
            //默认在办理中的状态,1，办理中，2已结束，3取消，4作废，5退回,6删除，7草稿
            String oldWh = sendfile.getFileNoSee();
            //已有文号修改  旧文号存在 旧文号不等于新文号 文号id不为空
            if (StringUtils.isNotEmpty(oldWh) && !oldWh.equals(wh) && StringUtils.isNotEmpty(fileNoId)) {
                logger.error("oldwh:"+oldWh);
                logger.error("已有文号修改  旧文号存在 旧文号不等于新文号 文号id不为空");
                logger.error("fileNoId:"+fileNoId);
                Boolean hasWh = govSendSaveFileNoService.checkSendFileNo(oldWh, fileNoId);//旧的文号是否保存
                logger.error("hasWh:"+hasWh);
                isUsed = govSendSaveFileNoService.checkSendFileNo(wh, fileNoId);//当前文号是否保存
                logger.error("wh:"+wh);
                logger.error("fileNoId:"+fileNoId);
                logger.error("isUsed:"+isUsed);
                //当前文号未使用
                if (!isUsed) {
                    //没有保存旧文号
                    if (!hasWh) {
                        DocSendSavefileno saveSendFileNo = govSendSaveFileNoService.addSendFileNo(wh, whYear, whNum, useName, fileNoId);
                        sendfile.setSavefilenoId(saveSendFileNo.getId());
                    } else {
                        govSendSaveFileNoService.deleteSenFileNo(oldWh);
                        DocSendSavefileno saveSendFileNo = govSendSaveFileNoService.addSendFileNo(wh, whYear, whNum, useName, fileNoId);
                        sendfile.setSavefilenoId(saveSendFileNo.getId());
                    }
                } else {
                    logger.error("当前文号已被使用 不保存");
                    //当前文号已被使用 不保存
                    sendfile.setIssuedNumber(null);
                    sendfile.setFileNoSee(null);
                    wh = "";
                    super.editSave(sendfile);
                }
            } else if (StringUtils.isEmpty(oldWh) && StringUtils.isNotEmpty(fileNoId)) {
                //第一次保存文号 旧文号为空 文号id不为空
                logger.error("第一次保存文号 旧文号为空 文号id不为空");
                isUsed = govSendSaveFileNoService.checkSendFileNo(wh, fileNoId);//旧的文号是否保存
                logger.error("970行isUsed:"+isUsed);
                if (!isUsed) {
                    DocSendSavefileno saveSendFileNo = govSendSaveFileNoService.addSendFileNo(wh, whYear, whNum, useName, fileNoId);
                    sendfile.setSavefilenoId(saveSendFileNo.getId());
                } else {
                    //当前文号被使用 不保存文号
                    sendfile.setIssuedNumber(null);
                    sendfile.setFileNoSee(null);
                    wh = "";
                    super.editSave(sendfile);
                }
            } else if (StringUtils.isNotEmpty(oldWh) && oldWh.equals(wh) && StringUtils.isNotEmpty(fileNoId)) {
                //旧文号已存在 等于当前选的文号 文号未改变 不做操作
                logger.error("旧文号已存在 等于当前选的文号 文号未改变 不做操作");
                Boolean hasWh = govSendSaveFileNoService.checkSendFileNo(oldWh, fileNoId);//旧的文号是否保存
                logger.error("986行hasWh:"+hasWh);
                if (!hasWh) {
                    DocSendSavefileno saveSendFileNo = govSendSaveFileNoService.addSendFileNo(wh, whYear, whNum, useName, fileNoId);
                    sendfile.setSavefilenoId(saveSendFileNo.getId());
                }
            } else {
                //参数错误 文号id 没有 且旧文号是空 第一次选文号 不保存
                logger.error("参数错误 文号id 没有 且旧文号是空 第一次选文号 不保存");
                logger.error("994fileNoId"+fileNoId);
                logger.error("994oldWh"+oldWh);
                if (StringUtils.isEmpty(fileNoId) && StringUtils.isEmpty(oldWh)) {
                    sendfile.setIssuedNumber(null);
                    wh = "";
                }
                super.editSave(sendfile);
            }
            // 保存预留文号的数据,判断此次选择的文号是否在预留的文号中存在，如果有，需要更新预留文号的状态,旧的状态释放，新的状态修改为已使用
            String str = sendfile.getIssuedNumber();
            jgdz = saveIssueNum(corpId, jgdz, whYear, whNum, fileNoId, str);
            //处理流程名称，以及发文单位
            logger.error("1007wh"+wh);
            logger.error("1007jgdz"+jgdz);
            setSendFileCommonField(currentJg, wh, processName, sendfile, jgdz);

        }

        if (StringUtils.isEmpty(wh)) {
            //当前文号为空  该数据如果 是保存一半的数据  则置空该数据文号信息
            if (sendfile != null) {
                //if (StringUtils.isEmpty(sendfile.getFileNoSee()) || StringUtils.isEmpty(sendfile.getIssuedNumber())) {
                sendfile.setIssuedNumber(null);
                sendfile.setFileNoSee(null);
                super.editSave(sendfile);
                //}
            }
        }

        if (isUsed) {
            return "isUsed";
        } else {
            return "notUsed";
        }
    }
    public String convertDocumentNumber(String wh) {
        // 正则表达式匹配两种格式：文号〔年份〕第X期 或 文号〔年份〕X号
        Pattern pattern = Pattern.compile("^(.*?)〔(\\d{4})〕(?:第(\\d+)期|(\\d+)号)$");
        Matcher matcher = pattern.matcher(wh);
        if (matcher.find()) {
            String docName = matcher.group(1);
            String year = matcher.group(2);
            String number = matcher.group(3) != null ? matcher.group(3) : matcher.group(4);
            String suffix = matcher.group(3) != null ? "期" : "号";
            String prefix = matcher.group(3) != null ? "第" : "";
            return String.format("(%s)〔%s〕%s|%s|%s", docName, year, prefix, number, suffix);
        }
        return wh;
    }

    /**
     * 保存发文的其他信息
     *
     * @param type
     * @param sendfile
     * @param flag
     * @param symbolId
     * @param processName
     * @return
     */
    public String saveSendfileInfo(String type, GovSendFile sendfile, String flag, String symbolId, String processName, String currentJg) {
        //保存流程状态
        if (StringUtils.isNotEmpty(type)) {
            if (sendfile != null) {
                if ("0".equals(type)) {
                    sendfile.setFlowStatus("7");
                } else if ("1".equals(type)) {
                    sendfile.setFlowStatus("1");
                } else if ("3".equals(type)) {
                    if ("4".equals(flag)) {
                        sendfile.setFlowStatus("4");
                    } else {
                        sendfile.setFlowStatus("2");
                    }
                } else if ("2".equals(type)) {
                    sendfile.setFlowStatus("1");
                }
                super.editSave(sendfile);
            }
        }
        //保存统一标识
        try {
            if (StringUtils.isNotEmpty(symbolId)) {
                if (sendfile != null) {
                    sendfile.setSymbolId(symbolId);
                    super.editSave(sendfile);
                }
            }
            if (StringUtils.isBlank(sendfile.getProcessNameSta()) && StringUtils.isNotBlank(processName)) {
                sendfile.setProcessNameSta(processName);
                sendfile.setProcessName(processName);
            }
            if (sendfile.getSponsorUnit() == null || "".equals(sendfile.getSponsorUnit())) {
                String orgid = sendfile.getCreatedOrg();
                currentJg = "";
                currentJg = govBaseSetService.getUnitIdByOrgId(orgid, currentJg);
                sendfile.setSponsorUnit(currentJg);
            }
        } catch (Exception e) {
            e.printStackTrace();
            logger.error("保存发文流程失败！" + e);
        }
        return "";
    }

    /**
     * @param corpId
     * @param jgdz
     * @param whYear
     * @param whNum
     * @param fileNoId
     * @param str
     * @name: saveIssueNum
     * @description: 更新预留文号
     * @return: java.lang.String
     * @date: 2021/9/23 16:13
     * @auther: fsx
     */
    private String saveIssueNum(String corpId, String jgdz, String whYear, String whNum, String fileNoId, String str) {
        String newStr = "";
        String nf = "";
        String hm = "";
        if (StringUtils.isNoneEmpty(str)) {
            //机关带子，年份，号码
            if (str.indexOf("]") > -1) {//不显示文号名
                newStr = str.split("]")[1];
                jgdz = str.split("]")[0].replace("[", "");
                if (newStr.indexOf('-') > -1) {//不显示年份
                    nf = newStr.split("-")[1];
                    hm = newStr.split("-")[2];
                    if (hm.indexOf("|") > -1) {
                        hm = hm.split("\\|")[1];
                    }
                } else {
                    hm = newStr.split("〕")[1];
                    if (hm.indexOf("|") > -1) {
                        hm = hm.split("\\|")[1];
                    }
                    nf = newStr.split("〕")[0].split("〔")[1];
                }
            } else if (str.indexOf(')') > -1) {//显示文号名
                jgdz = str.split("\\)")[0].replace("(", "");
                newStr = str.split("\\)")[1];
                if (newStr.indexOf('-') > -1) {//不显示年份
                    nf = newStr.split("-")[1];
                    hm = newStr.split("-")[2];
                    if (hm.indexOf("|") > -1) {
                        hm = hm.split("\\|")[1];
                    }
                } else {
                    hm = newStr.split("〕")[1];
                    if (hm.indexOf("|") > -1) {
                        hm = hm.split("\\|")[1];
                    }
                    nf = newStr.split("〕")[0].split("〔")[1];
                }
            }
            sendReserveFileNoService.updateSendFileNo(nf, hm, fileNoId, corpId, "1");
            sendReserveFileNoService.updateSendFileNo(whYear, whNum, fileNoId, corpId, "2");
        }
        return jgdz;
    }

    /**
     * 发文流程中后台默认字段的处理
     *
     * @param currentJg
     * @param wh
     * @param processName
     * @param jgdz
     * @param sendfile
     * @param jgdz
     */
    private void setSendFileCommonField(String currentJg, String wh, String processName, GovSendFile sendfile, String jgdz) {
        //公文标识放到生成正式公文之前处理
        //sendfile.setIdentifier(identifier);
        sendfile.setFileNoSee(wh);
        sendfile.setJgdz(jgdz);
    }


    /**
     * 退回，取消按钮，需要对公文主表的状态进行更新
     *
     * @param request
     * @param type        类型
     * @param businessKey 公文数据id
     * @name: updateSendFileByButton
     * @return: org.ezplatform.core.web.view.OperationResult
     * @date: 2022/10/19 11:38
     */
    @RequestMapping(value = "/updateSendFileByButton", method = RequestMethod.GET)
    @ResponseBody
    public OperationResult updateSendFileByButton(HttpServletRequest request) {
        //WebUser user = WebUtils.getCurrentUser();
        String type = request.getParameter("type") == null ? "" : request.getParameter("type");
        String businessKey = request.getParameter("businessKey") == null ? "" : request.getParameter("businessKey");
        if (!DocumentValidateUtil.validateParamsString(type, businessKey)) {
            throw new ValidationException("非法参数");
        }

        GovSendFile sendfile = sendFileService.findOne(businessKey);
        if ("cancel".equals(type)) {
            sendfile.setFlowStatus("3");//取消
            super.editSave(sendfile);
            //更新发文字号的使用状态。
            govSendSaveFileNoService.updateSendFileNoStatus("3", sendfile.getFileNoSee());
        } else if ("delete".equals(type)) {
            sendfile.setFlowStatus("4");//作废
            super.editSave(sendfile);
            govSendSaveFileNoService.updateSendFileNoStatus("4", sendfile.getFileNoSee());
        } else if ("back".equals(type)) {
            sendfile.setFlowStatus("5");//退回
            super.editSave(sendfile);
            govSendSaveFileNoService.updateSendFileNoStatus("5", sendfile.getFileNoSee());
        }
        return OperationResult.buildSuccessResult("操作成功");
    }


    /**
     * 发文查询列表数据
     * yzn
     *
     * @param request
     * @param title             标题
     * @param issuedNumber      文号
     * @param dealStatus        办理状态
     * @param createName        发起人
     * @param startTime         开始时间
     * @param endTime           结束时间
     * @param processNameQuery  流程名称
     * @param archiveStatus     归档状态
     * @param processCode       流程编码
     * @param nowDealMan        当前办理人
     * @param operatorSearchMan 经办人
     * @param commentsSearch    批示意见
     * @param draftingUnit      拟稿单位
     * @return
     */
    @SuppressWarnings({"rawtypes", "unchecked"})
    @RequestMapping(value = "/list", method = RequestMethod.GET)
    @ResponseBody
    public Page list(HttpServletRequest request) {
        WebUser user = WebUtils.getCurrentUser();
        String corpId = user.getCorpId();
        String title = ValidateUtils.filter(request.getParameter("title"));
        title = ParamEscapeUtil.unescape(title);
        /*String title = request.getParameter("title");*/
        String issuedNumber = ValidateUtils.filter(request.getParameter("issuedNumber"));

        String page = ValidateUtils.filter(request.getParameter("page"));
        String rows = ValidateUtils.filter(request.getParameter("rows"));

        String dealStatus = ValidateUtils.filter(request.getParameter("dealStatus"));
        String createName = ValidateUtils.filter(request.getParameter("createName"));
        String startTime = ValidateUtils.filter(request.getParameter("startTime"));
        String endTime = ValidateUtils.filter(request.getParameter("endTime"));
        String processName = ValidateUtils.filter(request.getParameter("processNameQuery"));
        String archiveStatus = ValidateUtils.filter(request.getParameter("archiveStatus"));
        String processCode = ValidateUtils.filter(request.getParameter("processCode"));
        String nowDealMan = ValidateUtils.filter(request.getParameter("nowDealMan"));
        String operatorSearchMan = ValidateUtils.filter(request.getParameter("operatorSearchMan"));
        String commentsSearch = ValidateUtils.filter(request.getParameter("commentsSearch"));
        String draftingUnit = ValidateUtils.filter(request.getParameter("draftingUnit"));
        String startUserGroupName = request.getParameter("startUserGroupName");
        //处理标题特殊字数
        String newTitle = "";
        /*if (StringUtils.isNotEmpty(title)) {
            int in = title.indexOf("&amp;");
            if (title.indexOf("&amp;") > -1) {
                newTitle = title.replaceAll("&amp;", "&");
                title = newTitle;
            }
        }*/
        Map<String, String> param = new HashMap<String, String>();

        param.put("issuedNumber", issuedNumber);
        param.put("dealStatus", dealStatus);
        param.put("page", page);
        param.put("rows", rows);
        param.put("createName", createName);
        param.put("startTime", startTime);
        param.put("endTime", endTime);
        param.put("processName", processName);
        param.put("archiveStatus", archiveStatus);
        param.put("processCode", processCode);
        param.put("nowDealMan", nowDealMan);
        param.put("operatorSearchMan", operatorSearchMan);
        param.put("commentsSearch", commentsSearch);
        param.put("draftingUnit", draftingUnit);

        Pageable pageable = PropertyFilter.buildPageableFromHttpRequest(request);
        if (!DocumentValidateUtil.validateParamByMap(param, null, null)) {
            return  new PageImpl(new ArrayList<Map>(),pageable,0);
        }
        param.put("startUserGroupName",startUserGroupName);
        param.put("title", title);
        List<PropertyFilter> localList = PropertyFilter.buildFiltersFromHttpRequest(GovSendFile.class, request);

        Page pageResult = sendFileService.getList(pageable, localList, corpId, param);
        return pageResult;
    }


    /**
     * 删除
     *
     * @param ids               公文数据id
     * @param processInstanceId 流程实例
     * @param secdatacode       校验码
     * @name: delete
     * @return: org.ezplatform.core.web.view.OperationResult
     * @date: 2022/10/19 11:41
     */
    @WebsocketCode({WebsocketConstant.GOADEAL,WebsocketConstant.GOADEALLIST,WebsocketConstant.GOAEFFICIENCYSTATISTICS,WebsocketConstant.UNITEDAPPROVE,WebsocketConstant.MSGUMC,WebsocketConstant.SYSREMIND})
    @RequestMapping(value = "/delete", method = RequestMethod.POST)
    @ResponseBody
    public OperationResult delete(String ids, String processInstanceId, String secdatacode) {

        if (!DocumentValidateUtil.validateParamsString(ids, processInstanceId)) {
            throw new ValidationException("非法参数");
        }
        if (!DocumentValidateUtil.validateParamSecdatacode(secdatacode)) {
            throw new ValidationException("非法参数");
        }

        WebUser user = WebUtils.getCurrentUser();
        //处理平行越权问题
        boolean checkData = false;
        if (StringUtils.isNotEmpty(secdatacode)) {
            checkData = DealFieldEncodeUtils.checkData("id" + ids, "goa_document", secdatacode);
        }
        if (!checkData) {
            return OperationResult.buildFailureResult("数据出错,请重新操作");
        }
        String corpId = user.getCorpId();
        String title = sendFileService.findOne(ids).getTitle();
        List<Map> taskIdlist = new ArrayList<>();
        List<String> receiverList = new ArrayList<>();
        if (StringUtils.isNotBlank(processInstanceId)) {
            List<Map> sendFileInfoByProcId = govDocHandlingService.getTitleByProcId(processInstanceId);
            if (sendFileInfoByProcId != null && !sendFileInfoByProcId.isEmpty()) {
                title = sendFileInfoByProcId.get(0).get("text_").toString();
            }
            taskIdlist = sendFileService.getTaskIdByProcId(processInstanceId);
            if (taskIdlist != null && !taskIdlist.isEmpty()) {
                for (int i = 0; i < taskIdlist.size(); i++) {
                    Map map = new HashMap();
                    map.put("corpId", corpId);
                    map.put("bizMsgIds", taskIdlist.get(i).get("taskId"));
                    map.put("userIds", taskIdlist.get(i).get("userId"));
                    map.put("orgIds", user.getOrgId());
                    map.put("moduleCode", "goa_document");
                    map.put("moduleZdyCode", "goa_doc_sendfile_pending");
                    //logger.error("公文删除角标==========="+ JsonUtils.writeValueAsString(map));
                    RestClient restClient = new RestClient(false);
                    String resulrString = mobileCommonApiService.clearBadge(map,user.getJwtToken());
                    //logger.error("公文删除角标 结果==========="+ resulrString);
                    Map param = new HashMap();
                    param.put("id", taskIdlist.get(i).get("taskId"));
                    param.put("userId", taskIdlist.get(i).get("userId"));
                    String receiverId = StringUtils.null2String(taskIdlist.get(i).get("userId"));
                    receiverList.add(receiverId);
                    //param.put("isAllUserType","1");
                    //logger.error("公文删除待办==========="+ JsonUtils.writeValueAsString(map));
                    String result = messageApiService.delTododone(map,user.getJwtToken());
                    //logger.error("公文删除待办 结果==========="+ result);
                }
            }
        }
        // 记录日志
        if (logService.checkOptLog("0", LogConstant.SENDFILE_LOG_04, TOKEN)) {
            logService.saveModuleLog(LogConstant.SENDFILE_LOG_04, title, "");
        }
        OperationResult result = sendFileService.delete(ids, processInstanceId, user, corpId, TOKEN);

        //删除版本记录
        Map<String, String> delParamMap = new HashMap();
        delParamMap.put("processInstanceId", processInstanceId);
        approveApiService.delHiFormOfdByProInstanceId(delParamMap,user.getJwtToken());

        WebsocketUtils.setReceiverById(receiverList);
        return result;
    }


    /**
     * 判断此签报流程有没有分发和传阅操作
     *
     * @param request
     * @param id      数据id
     * @name: checkFaAndCy
     * @return: java.util.Map<java.lang.String, java.lang.String>
     * @date: 2022/10/19 11:42
     */
    @RequestMapping(value = "/checkFaAndCy", method = RequestMethod.GET)
    @ResponseBody
    public Map<String, String> checkFaAndCy(HttpServletRequest request) {
        Map<String, String> resultMap = new HashMap<String, String>();
        String id = request.getParameter("id");
        if (!DocumentValidateUtil.validateParamsString(id)) {
            throw new ValidationException("非法参数");
        }
        resultMap = govCommonService.checkFaAndCy(id);
        return resultMap;
    }


    /**
     * 是否可以同步至信息
     *
     * @param request
     * @param businessKey 公文数据id
     * @param type        类型
     * @name: isCanSynToInfo
     * @return: java.util.Map<java.lang.String, java.lang.Object>
     * @date: 2022/10/19 11:42
     */
    @RequestMapping(value = "/isCanSynToInfo", method = RequestMethod.POST)
    @ResponseBody
    public Map<String, Object> isCanSynToInfo(HttpServletRequest request) {
        String businessKey = request.getParameter("businessKey") == null ? "" : request.getParameter("businessKey");
        String type = request.getParameter("type") == null ? "" : request.getParameter("type");
        if (!DocumentValidateUtil.validateParamsString(businessKey, type)) {
            throw new ValidationException("非法参数");
        }
        GovSendFile sendfile = sendFileService.findOne(businessKey);
        Map<String, Object> resultMap = new HashMap<String, Object>();
        resultMap.put("flowStatus", sendfile.getFlowStatus());
        if ("isShowSynToInfo".equals(type)) {
            return resultMap;
        }
        resultMap.put("attachment", sendfile.getAttachment());
        resultMap.put("formatfile", sendfile.getFormatFile());
        //附件id
        List<GovDocAttachment> attachmentList = govDocAttachmentService.getAttachListByDocumentId(businessKey);
        String syncInfoGoaAttchId = "";
        if (attachmentList != null && attachmentList.size() > 0) {
            for (int i = 0; i < attachmentList.size(); i++) {
                syncInfoGoaAttchId += attachmentList.get(i).getSysAttchmentId() + "|";
            }
            syncInfoGoaAttchId = syncInfoGoaAttchId.substring(0, syncInfoGoaAttchId.length() - 1);
        }
        resultMap.put("syncInfoGoaAttchId", syncInfoGoaAttchId);
        String docrecordId = "";
        String fileType = "";
        String filecontent = sendfile.getFileContent();
        String formatfile = sendfile.getFormatFile();
        if (StringUtils.isNotBlank(formatfile)) {
            docrecordId = formatfile;
            fileType = "ofd";
        } else {
            docrecordId = filecontent;
            fileType = "doc";
        }
        resultMap.put("filecontent", sendfile.getFileContent());
        resultMap.put("title", escapeExprSpecialWord(sendfile.getTitle()));
        if (StringUtils.isNoneBlank(sendfile.getPublishattribute())) {
            String name = sendFileService.getPublishattribute(sendfile.getPublishattribute());
        }

        if (StringUtils.isNotBlank(docrecordId)) {
            List<Map> list = govDocFileEditionService.getFileName(docrecordId, fileType);
            if (list != null && list.size() == 1) {
                String syncInfoGoaContentId = list.get(0).get("id").toString();
                String contentType = StringUtils.isNotBlank(list.get(0).get("id").toString())
                        ? govDocAttachmentDao.getSysContentType(list.get(0).get("id").toString()).get("content_type")
                        : "";
                Map newMap = copyFileUtils.copyFileByAttachId(syncInfoGoaContentId, escapeExprSpecialWord(sendfile.getTitle()));
                syncInfoGoaContentId = newMap.get("id") + "";
                resultMap.put("syncInfoGoaContentId", syncInfoGoaContentId);
                contentType = StringUtils.isNotBlank(list.get(0).get("id").toString())
                        ? govDocAttachmentDao.getSysContentType(list.get(0).get("id").toString()).get("content_type")
                        : "";
                Integer falg = StringUtils.isNotBlank(syncInfoGoaContentId)
                        ? govDocAttachmentDao.updateSysContentType(contentType, syncInfoGoaContentId)
                        : 0;


            }
        }
        if ("不予公开".equals(sendfile.getPublishattribute())) {
            resultMap.put("publishattribute", '1');
        } else {
            resultMap.put("publishattribute", '0');
        }
        return resultMap;
    }

    /**
     * HTML特殊字符转换处理
     *
     * @param keyword String
     * @return String
     */
    public String escapeExprSpecialWord(String keyword) {
        if (StringUtils.isNotEmpty(keyword)) {
            String[] fbsArr = {"\\", "/", ":", "*", "?", "\"", "<", ">", "《", "》", "|", "!", "@", "#", "$", "%", "^", "&", "(", ")", "-", "{", "}", "~"};
            for (String key : fbsArr) {
                if (keyword.contains(key)) {
                    keyword = keyword.replace(key, "");
                }
            }
        }
        return keyword;
    }

    /**
     * 获取公文标识
     *
     * @param request
     * @param fileTypeName 文件类型
     * @param fileNoYear   文号年份
     * @param sendFileNo   文号
     * @name: getDocumentMark
     * @return: org.ezplatform.core.web.view.OperationResult
     * @date: 2022/10/19 11:43
     */
    @RequestMapping(value = "/getDocumentMark", method = RequestMethod.POST)
    @ResponseBody
    public OperationResult getDocumentMark(HttpServletRequest request, String fileTypeName, String fileNoYear, String sendFileNo) {

        if (!DocumentValidateUtil.validateParamsString(fileTypeName, fileNoYear)) {
            throw new ValidationException("非法参数");
        }
        WebUser user = WebUtils.getCurrentUser();
        String orgid = user.getOrgId();
        String zzbm = user.getOrgUnitCode();
        if (StringUtils.isEmpty(zzbm)) {
            zzbm = "XXX";
        }
        GovBSUtil bsUtil = new GovBSUtil();
        String identifier = "";
        if (StringUtils.isBlank(fileTypeName)) {
            fileTypeName = "其他";
        }
        String unitId = govBaseSetService.getUnitIdByOrgId(orgid, "");
        String orgUnitCode = govBaseSetService.orgUnitCode(unitId);
        if (StringUtils.isEmpty(orgUnitCode)) {
            orgUnitCode = "91110108753321386X";
        }
        String serialNumber = "";
        if (StringUtils.isNotEmpty(sendFileNo)) {
            if (sendFileNo.indexOf("]") > -1) {//不显示文号名
                String newStr = "";
                newStr = sendFileNo.split("]")[1];
                if (newStr.indexOf('-') > -1) {//不显示年份
                    serialNumber = newStr.split("-")[2];
                } else {
                    serialNumber = newStr.split("〕")[1];
                }
            } else if (sendFileNo.indexOf(')') > -1) {//显示文号名
                String newStr = sendFileNo.split("\\)")[1];
                if (newStr.indexOf('-') > -1) {//不显示年份
                    serialNumber = newStr.split("-")[2];
                } else {
                    serialNumber = newStr.split("〕")[1];
                }
            } else if (sendFileNo.indexOf('〕') > -1) {//显示文号名
                String newStr = sendFileNo.split("〕")[1];
                if (newStr.indexOf('-') > -1) {//不显示年份
                    serialNumber = newStr.split("-")[2];
                } else {
                    serialNumber = newStr.substring(0, newStr.length() - 1);
                }
            } else {
                serialNumber = sendFileNo;
            }
        }

        try {
            identifier = bsUtil.getGovBS(zzbm.toUpperCase(), fileNoYear, fileTypeName, serialNumber, orgUnitCode);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return OperationResult.buildSuccessResult("操作成功", identifier);
    }

    /**
     * 发文查询相关操作记载日志
     *
     * @param request
     * @param logTitle  日志标题
     * @param processId 流程实例id
     * @name: addLog
     * @return: org.ezplatform.core.web.view.OperationResult
     * @date: 2022/10/19 11:44
     */
    @RequestMapping(value = "/addLog")
    @ResponseBody
    public OperationResult addLog(HttpServletRequest request) {
        String title = ValidateUtils.filter(request.getParameter("logTitle"));
        String processId = ValidateUtils.filter(request.getParameter("processId"));

        if (!DocumentValidateUtil.validateParamsString(title, processId)) {
            throw new ValidationException("非法参数");
        }
        //去除不必要查询
		/*if (StringUtils.isNotBlank(processId)) {
			List<Map> sendFileInfoByProcId = govDocHandlingService.getTitleByProcId(processId);
			if (sendFileInfoByProcId != null && !sendFileInfoByProcId.isEmpty()) {
				title = sendFileInfoByProcId.get(0).get("text_").toString();
			}
		}*/
        if (StringUtils.isNotBlank(title)) {
            if (logService.checkOptLog("0", LogConstant.SENDFILE_LOG_03, TOKEN)) {
                logService.saveModuleLog(LogConstant.SENDFILE_LOG_03, title, "");
            }
        }

        return OperationResult.buildSuccessResult();
    }

    /**
     * 新增/修改保存表单之后，需要对态等字段处理。 此方法废弃
     *
     * @param request
     * @param type        类型
     * @param businessKey 公文数据Id
     * @name: updateInfo
     * @return: org.ezplatform.core.web.view.OperationResult
     * @date: 2022/10/19 11:44
     */
    @RequestMapping(value = "/updateinfo", method = RequestMethod.POST)
    @ResponseBody
    public OperationResult updateInfo(HttpServletRequest request) {
        //WebUser user = WebUtils.getCurrentUser();
        //String unit = user.getInstitutionId();
        String unit = "";
        String type = request.getParameter("type") == null ? "" : request.getParameter("type");
        String businessKey = request.getParameter("businessKey") == null ? "" : request.getParameter("businessKey");
        if (!DocumentValidateUtil.validateParamsString(businessKey, type)) {
            throw new ValidationException("非法参数");
        }
        if (StringUtils.isNoneBlank(businessKey)) {
            String[] split = businessKey.split(",");
            if (split != null) {
                for (int i = 0; i < split.length; i++) {
                    GovSendFile sendFile = sendFileService.findOne(split[i]);
                    //如果是新增
                    if ("1".equals(type) || "0".equals(type)) {
                        //默认在办理中的状态,1，办理中，2已结束，3取消，4作废，5退回,6删除，7草稿
                        if ("0".equals(type)) {
                            sendFile.setFlowStatus("7");
                        } else if ("1".equals(type)) {
                            sendFile.setFlowStatus("1");//草稿
                            String govFormType = request.getParameter("govFormType") == null ? "" : request.getParameter("govFormType");
                            String sendProcessTitle = request.getParameter("sendProcessTitle") == null ? "" : request.getParameter("sendProcessTitle");
                            if (!"".equals(govFormType) && !"6".equals(govFormType) && logService.checkOptLog("0", LogConstant.GOA_DOCUMENT_START_02, TOKEN)) {
                                logService.saveModuleLog(LogConstant.GOA_DOCUMENT_START_02, sendProcessTitle, "");
                            }
                        }
                        //if(StringUtils.isBlank(signReportFile.getSponsorUnit())) {
                        String orgid = sendFile.getCreatedOrg();
                        unit = govBaseSetService.getUnitIdByOrgId(orgid, unit);
                        sendFile.setSponsorUnit(unit);
                        //}
                    } else if ("2".equals(type)) {
                        sendFile.setFlowStatus("1");//办理中
                    } else if ("3".equals(type)) {
                        if (sendFile != null) {
                            sendFile.setFlowStatus("2");//已结束
                        }
                    }
                    try {
                        super.editSave(sendFile);
                    } catch (Exception e) {
                        return OperationResult.buildSuccessResult("保存失败");
                    }
                }
            }
        }
        return OperationResult.buildSuccessResult("保存成功");
    }


    /**
     * 插入查看操作的日志
     * @name: insertLookLog
     * @param request
     * @param title 标题
     * @return: void
     * @date: 2022/10/19 11:45
     *
    */
    @RequestMapping(value = "/insertLookLog", method = RequestMethod.POST)
    @ResponseBody
    public void insertLookLog(HttpServletRequest request, String title) {
        if (!DocumentValidateUtil.validateParamsString(title)) {
            throw new ValidationException("非法参数");
        }
        // 记录日志
        if (logService.checkOptLog("0", "goa_document:flowQuery:03", TOKEN)) {
            logService.saveModuleLog("goa_document:flowQuery:03", title, "");
        }
    }

    /**
     * 插入导出操作的日志
     * @param request
     * @param fileCount 文件数量
     * @return
     */
    @RequestMapping(value = "/addExportLog", method = RequestMethod.POST)
    @ResponseBody
    public void addExportLog(HttpServletRequest request, String fileCount) {
        if (!DocumentValidateUtil.validateParamsString(fileCount)) {
            throw new ValidationException("非法参数");
        }
        // 记录日志
        if (logService.checkOptLog("0", LogConstant.SENDFILE_LOG_16, TOKEN)) {
            logService.saveModuleLog(LogConstant.SENDFILE_LOG_16, "发文查询导出" + fileCount + "个文件", "");
        }
    }

    /**
     * 保存米卡日志
     * @name: getParamsBySearch
     * @param request
     * @param secdatacode 检验码
     * @param fromWhere 来安
     * @return: java.util.Map<java.lang.String,java.lang.String>
     * @date: 2022/10/19 11:45
     *
    */
    @RequestMapping(value = "/getParams", method = RequestMethod.GET)
    @ResponseBody
    public Map<String, String> getParamsBySearch(HttpServletRequest request) {

        //鉴定是否平行越权
        Map<String, String> resultMap = new HashMap<String, String>();
        String id = request.getParameter("id");
        String secdatacode = request.getParameter("secdatacode");
        String fromWhere = request.getParameter("fromWhere");
        if (!DocumentValidateUtil.validateParamsString(id, fromWhere)) {
            throw new ValidationException("非法参数");
        }
        if (!DocumentValidateUtil.validateParamSecdatacode(secdatacode)) {
            throw new ValidationException("非法参数");
        }
        boolean checkData = false;
        if (StringUtils.isNotEmpty(secdatacode)) {

            if (StringUtils.isNotEmpty(fromWhere) && "scrabox".equals(fromWhere)) {
                List<String> dataList = new ArrayList<String>();
                String dataId = request.getParameter("dataId");
                //id的校验
                String businessKeyData = "businessKey" + id;
                String idData = "id" + dataId;
                dataList.add(businessKeyData);
                dataList.add(idData);
                checkData = DealFieldEncodeUtils.checkDataList(dataList, "goa_document", secdatacode);
            } else {
                checkData = DealFieldEncodeUtils.checkData("id" + id, "goa_document", secdatacode);
            }

        }
        if (!checkData) {
            String checkFlag = "false";
            resultMap.put("checkFlag", checkFlag);
            return resultMap;
        }
        resultMap = sendFileService.getParamsBySearch(id);
        String editType = request.getParameter("editType");
        String category = request.getParameter("category");
        String title = ValidateUtils.filter(request.getParameter("title"));
        //增加日志记录操作

        Runnable runnable = new Runnable() {
            @Override
            public void run() {
                if ("view".equals(editType) && "goa_doc_receivefile".equals(category)) {
                    if (logService.checkOptLog("0", LogConstant.RECEIVEFILE_LOG_03, TOKEN)) {
                        logService.saveModuleLog(LogConstant.RECEIVEFILE_LOG_03, title, "", (String) null, request);
                    }
                } else if ("view".equals(editType) && "goa_doc_sendfile".equals(category)) {
                    if (StringUtils.isNotBlank(title)) {
                        if (logService.checkOptLog("0", LogConstant.SENDFILE_LOG_03, TOKEN)) {
                            logService.saveModuleLog(LogConstant.SENDFILE_LOG_03, title, "", (String) null, request);
                        }
                    }
                }
            }
        };
        Thread thread = new Thread(runnable);
        thread.start();
        return resultMap;
    }


    /**
     * 通过id获取文号
     * @param request
     * @param id 文号id
     * @name: getFileNoById
     * @return: org.ezplatform.core.web.view.OperationResult
     * @date: 2021/2/2 10:44
     * @auther: fsx
     */
    @RequestMapping(value = "/getFileNoById", method = RequestMethod.GET)
    @ResponseBody
    public OperationResult getFileNoById(HttpServletRequest request, String id) {
        if (!DocumentValidateUtil.validateParamsString(id)) {
            throw new ValidationException("非法参数");
        }
        if (StringUtils.isNotEmpty(id)) {
            GovSendFileNum GovSendFileNum = govSendFileNumService.findOne(id);
            if (GovSendFileNum != null) {
                return OperationResult.buildSuccessResult("获取成功", GovSendFileNum);
            }
        }
        return OperationResult.buildFailureResult("获取失败");
    }


    /**
     * 获取流程内页自己渲染的数据的值
     * @param id 公文数据id
     * @return
     * @throws
     */
    @RequestMapping(value = "/getMyOperateField", method = {RequestMethod.POST})
    @ResponseBody
    public Map<String, String> getMyOperateField(String id) {
        if (!DocumentValidateUtil.validateParamsString(id)) {
            throw new ValidationException("非法参数");
        }
        StringBuffer sql = new StringBuffer();
        Map paramMap = new HashMap();
        sql.append(" select t1.file_no_id id  from  goa_doc_send_savefileno t1 LEFT JOIN goa_doc_sendfile t2 on  ");
        sql.append(" t1.id=t2.savefileno_id where t2.id=:id ");
        paramMap.put("id", id);
        List<Map> list = sendFileService.findByListNativeQuery(sql.toString(), "", paramMap);
        Map<String, String> result = new HashMap<String, String>();
        if (CollectionUtils.isNotEmpty(list) && list.size() == 1) {
            String filenoid = list.get(0).get("id") == null ? "" : list.get(0).get("id").toString();
            result.put("filenoid", filenoid);

        }
        return result;
    }

    /**
     * 调用过程完成后保存业务数据
     * @param request
     * @param olddataid 原流程业务数据id
     * @param newdataid 现业务数据id
     * @param category 公文类型
     * @name: callProcedureSaveBusinessData
     * @return: org.ezplatform.core.web.view.OperationResult
     * @auther: huwei
     */
    @RequestMapping(value = "/callProcedureSaveBusinessData", method = RequestMethod.GET)
    @ResponseBody
    public OperationResult callProcedureSaveBusinessData(HttpServletRequest request, String olddataid, String newdataid, String category) {
        WebUser user = WebUtils.getCurrentUser();
        if (!DocumentValidateUtil.validateParamsString(olddataid, newdataid, category)) {
            throw new ValidationException("非法参数");
        }
        if (StringUtils.isNotEmpty(olddataid) && StringUtils.isNotEmpty(newdataid)) {
            if ("goa_doc_sendfile".equals(category)) {
                GovSendFile oldG = sendFileService.findOne(olddataid);
                GovSendFile newG = sendFileService.findOne(newdataid);
                // 正式公文
                newG.setFormatFile(oldG.getFormatFile());
                // 正文
                newG.setFileContent(oldG.getFileContent());
                // 正文类型
                newG.setContentType(oldG.getContentType());
                // 清稿件recordId
                newG.setRevisionFile(oldG.getRevisionFile());
                // 正文控件类型
                newG.setMainTextClient(oldG.getMainTextClient());
                // 正文文件类型
                newG.setMainTextFileExt(oldG.getMainTextFileExt());
                newG.setFlowStatus("1");
                sendFileService.save(newG);
            } else if ("goa_doc_receivefile".equals(category)) {
                GovDocReceiveFile oldG = GovDocReceiveFileService.findOne(olddataid);
                GovDocReceiveFile newG = GovDocReceiveFileService.findOne(newdataid);
                // 正式公文
                newG.setFormatFile(oldG.getFormatFile());
                // 正文
                newG.setFileContent(oldG.getFileContent());
                // 正文类型
                newG.setContentType(oldG.getContentType());
                // 清稿件recordId
                newG.setRevisionFile(oldG.getRevisionFile());
                // 正文控件类型
                newG.setMainTextClient(oldG.getMainTextClient());
                // 正文文件类型
                newG.setMainTextFileExt(oldG.getMainTextFileExt());
                newG.setFlowStatus("1");
                GovDocReceiveFileService.save(newG);
            } else if ("goa_doc_signreport".equals(category)) {
                DocSignreport oldG = signQueryService.findOne(olddataid);
                DocSignreport newG = signQueryService.findOne(newdataid);
                // 正式公文
                newG.setFormatFile(oldG.getFormatFile());
                // 正文
                newG.setFileContent(oldG.getFileContent());
                // 正文类型
                newG.setContentType(oldG.getContentType());
                // 清稿件recordId
                newG.setRevisionFile(oldG.getRevisionFile());
                // 正文控件类型
                newG.setMainTextClient(oldG.getMainTextClient());
                // 正文文件类型
                newG.setMainTextFileExt(oldG.getMainTextFileExt());
                newG.setFlowStatus("1");
                signQueryService.save(newG);
            }
            // 处理附件
            List<GovDocAttachment> list = this.govDocAttachmentDao.getAllAttachmentListByDocument(olddataid);
            List<GovDocAttachment> savelist = new ArrayList<GovDocAttachment>();
            if (list != null && list.size() > 0) {
                for (int i = 0, size = list.size(); i < size; i++) {
                    GovDocAttachment attachment = list.get(i);
                    GovDocAttachment n = new GovDocAttachment();
                    // 这里需要复制一份附件
                    Map newMap = copyFileUtils.copyFileByAttachId(attachment.getSysAttchmentId(), null);
                    n.setDocumentSource(attachment.getDocumentSource());
                    n.setAttachmentName(attachment.getAttachmentName());
                    n.setSortNo(attachment.getSortNo());
                    n.setIsDelete(0);
                    n.setSecurityClassificat(attachment.getSecurityClassificat());
                    n.setFileSize(attachment.getFileSize());
                    n.setSysAttchmentId(StringUtils.null2String(newMap.get("id")));
                    n.setFileSource(attachment.getFileSource());
                    n.setAttachmentReal(StringUtils.null2String(newMap.get("fileName")));
                    n.setDocumentId(newdataid);
                    n.setRecordId(attachment.getRecordId());
                    savelist.add(n);
                }
            }
            govDocAttachmentService.save(savelist);
            // 处理版本记录
            List<GovDocFileEdition> savedoclist = new ArrayList<GovDocFileEdition>();
            // 正文
            List<GovDocFileEdition> listflow = fileEditionService.getListByGoaId(olddataid, "1");
            GovDocFileEdition gflow = null;
            if (CollectionUtils.isNotEmpty(listflow)) gflow = listflow.get(0);
            if (gflow != null) {
                GovDocFileEdition g = new GovDocFileEdition();
                // 公文id
                g.setGoaId(newdataid);
                // 版本号
                g.setTextVersion(gflow.getTextVersion());
                // 生成版本人员
                g.setVersionName(user.getUserId());
                // 生成版本时间
                g.setVersionTime(new Date());
                // 生成版本部门
                g.setVersionUnit(gflow.getVersionUnit());
                // 文件类型：1：正文版本，2：正式公文版本。
                g.setFileType(gflow.getFileType());
                // 历史版本附件id
                g.setFileId(gflow.getFileId());
                // 正文版本
                g.setStreamVersion(gflow.getStreamVersion());
                // 公文的recordId
                g.setRecordId(gflow.getRecordId());
                // 版本号名称
                g.setTextVersionName("V1");
                // 附件checksum
                g.setChecksum(gflow.getChecksum());
                // taskId
                g.setTaskId(gflow.getTaskId());
                if (StringUtils.isNotEmpty(gflow.getTaskId())) {
                    g.setTaskName(fileEditionService.getTaskName(gflow.getTaskId()));
                }
                // 是否回退生成的版本
                g.setIsRollback(gflow.getIsRollback());
                //是否隐藏:0-否;1是
                g.setIsHidden("0");
                //是否核稿:0-否;1是
                g.setIsReview("0");
                savedoclist.add(g);
            }
            // 版式
            List<GovDocFileEdition> listformat = fileEditionService.getListByGoaId(olddataid, "2");
            GovDocFileEdition gformat = null;
            if (CollectionUtils.isNotEmpty(listformat)) gformat = listformat.get(0);
            if (gformat != null) {
                GovDocFileEdition g = new GovDocFileEdition();
                // 公文id
                g.setGoaId(newdataid);
                // 版本号
                g.setTextVersion(gformat.getTextVersion());
                // 生成版本人员
                g.setVersionName(user.getUserId());
                // 生成版本时间
                g.setVersionTime(new Date());
                // 生成版本部门
                g.setVersionUnit(gformat.getVersionUnit());
                // 文件类型：1：正文版本，2：正式公文版本。
                g.setFileType(gformat.getFileType());
                // 历史版本附件id
                g.setFileId(gformat.getFileId());
                // 正文版本
                g.setStreamVersion(gformat.getStreamVersion());
                // 公文的recordId
                g.setRecordId(gformat.getRecordId());
                // 版本号名称
                g.setTextVersionName("V1");
                // 附件checksum
                g.setChecksum(gformat.getChecksum());
                // taskId
                g.setTaskId(gformat.getTaskId());
                if (StringUtils.isNotEmpty(gformat.getTaskId())) {
                    g.setTaskName(fileEditionService.getTaskName(gformat.getTaskId()));
                }
                // 是否回退生成的版本
                g.setIsRollback(gformat.getIsRollback());
                // 转版式文件要记录被专版的正文的版本
                g.setStreamVersion("V1");
                //是否隐藏:0-否;1是
                g.setIsHidden("0");
                //是否核稿:0-否;1是
                g.setIsReview("0");
                savedoclist.add(g);
            }
            if (CollectionUtils.isNotEmpty(savedoclist)) fileEditionService.save(savedoclist);
        }
        return OperationResult.buildSuccessResult("保存成功");
    }

    /**
     * 还原
     * @param ids 公文数据id
     * @param processInstanceId 流程实例id
     * @return
     */
    @RequestMapping(value = "/restore", method = RequestMethod.POST)
    @ResponseBody
    public OperationResult restore(HttpServletRequest request, String ids, String processInstanceId) {
        if (!DocumentValidateUtil.validateParamsString(processInstanceId)) {
            throw new ValidationException("非法参数");
        }
        WebUser user = WebUtils.getCurrentUser();
        String corpId = user.getCorpId();
        return sendFileService.restore(request, ids, processInstanceId, user, corpId, TOKEN);
    }

    /**
     * 分发件不同数据表转文获取发文表单信息
     * @param id 业数据id
     * @return
     * @throws
     */
    @RequestMapping(value = "/getTransferDataInfo", method = {RequestMethod.POST})
    @ResponseBody
    public Map<String, String> getTransferDataInfo(String id) {
        if (!DocumentValidateUtil.validateParamsString(id)) {
            throw new ValidationException("非法参数");
        }
        StringBuffer sql = new StringBuffer();
        Map paramMap = new HashMap();
        sql.append(" select t1.title,t1.file_no_see fileno,t1.emergency_degree emergencydegree,"
                + "t1.security_classification securityclassification,t2.name issuingagency from  goa_doc_sendfile t1 ");
        sql.append(" LEFT JOIN goa_doc_sendfile_scope t2 on t1.issuing_agency=t2.fieldDataValue  where t1.id=:id ");
        paramMap.put("id", id);
        List<Map> list = sendFileService.findByListNativeQuery(sql.toString(), "", paramMap);
        Map<String, String> result = new HashMap<String, String>();
        if (CollectionUtils.isNotEmpty(list) && list.size() == 1) {
            String title = list.get(0).get("title") == null ? "" : list.get(0).get("title").toString();
            result.put("title", title);
            String fileno = list.get(0).get("fileno") == null ? "" : list.get(0).get("fileno").toString();
            result.put("fileno", fileno);
            String emergencydegree = list.get(0).get("emergencydegree") == null ? "" : list.get(0).get("emergencydegree").toString();
            result.put("emergencydegree", emergencydegree);
            String securityclassification = list.get(0).get("securityclassification") == null ? "" : list.get(0).get("securityclassification").toString();
            result.put("securityclassification", securityclassification);
            String issuingagency = list.get(0).get("issuingagency") == null ? "" : list.get(0).get("issuingagency").toString();
            result.put("issuingagency", issuingagency);
        }
        return result;
    }

    /**
     * 保存流水号信息
     * @param request
     * @param dataId 数据id
     * @param bizId 流水号id
     * @param showValue 流水号值
     * @return
     */
    @RequestMapping(value = "/saveBizData", method = RequestMethod.POST)
    @ResponseBody
    public void saveBizData(HttpServletRequest request) {
        WebUser user = WebUtils.getCurrentUser();
        // 表单数据ID
        String dataId = request.getParameter("dataId");
        // 流水号ID
        String bizId = request.getParameter("bizId");
        // 选中的数据表值
        String showValue = request.getParameter("showValue");
        if (!DocumentValidateUtil.validateParamsString(dataId, bizId, showValue)) {
            throw new ValidationException("非法参数");
        }
        GovSendFile g = sendFileService.findOne(dataId);
        if (g != null) {
            g.setBizId(bizId);
            g.setBizShowValue(showValue);
            sendFileService.save(g);
        }
    }

    /**
     * 删除发文字号
     * @param request
     * @param ids 公文数据id
     * @param processInstanceId 流程实例id
     * @return
     */
    @RequestMapping(value = "/deleteFileNo", method = RequestMethod.POST)
    @ResponseBody
    public OperationResult deleteBids(HttpServletRequest request) {
        //业务数据id
        String ids = request.getParameter("ids");
        // 流程实例id
        String processInstanceId = request.getParameter("processInstanceId");
        if (!DocumentValidateUtil.validateParamsString(ids, processInstanceId)) {
            throw new ValidationException("非法参数");
        }
        try {
            if (ids != null && ids.length() > 0) {
                String[] idlist = ids.split(",");
                for (String id : idlist) {
                    GovSendFile gsf = this.sendFileService.findOne(id);
                    //释放文号
                    if (gsf != null && StringUtils.isNotBlank(gsf.getFileNoSee())) {
                        this.sendFileService.deleteFileNo(ids);
                    }
                }
            }
            return OperationResult.buildSuccessResult("释放成功");
        } catch (Exception e) {
            logger.error("deleteBids111111   文号释放失败：", e);
            return OperationResult.buildFailureResult("文号释放失败");
        }
    }

    /**
     * 校验数据合法性
     * @name: checkSecdatacode
     * @param request
     * @param dataId 公文数据id
     * @param secdatacode 校验码
     * @return: java.util.Map<java.lang.String,java.lang.String>
     * @date: 2022/10/19 11:50
     *
    */
    @RequestMapping(value = "/checkSecdatacode", method = RequestMethod.GET)
    @ResponseBody
    public Map<String, String> checkSecdatacode(HttpServletRequest request) {
        //处理平行越权问题
        Map<String, String> reMap = new HashMap<>();
        String dataId = request.getParameter("dataId");
        String secdatacode = request.getParameter("secdatacode");
        if (!DocumentValidateUtil.validateParamsString(dataId)) {
            throw new ValidationException("非法参数");
        }
        if (!DocumentValidateUtil.validateParamSecdatacode(secdatacode)) {
            throw new ValidationException("非法参数");
        }
        boolean checkData = false;
        if (StringUtils.isNotEmpty(secdatacode)) {
            checkData = DealFieldEncodeUtils.checkData("id" + dataId, "goa_document", secdatacode);
        }
        if (!checkData) {
            reMap.put("checkFlag", "false");
        }
        return reMap;


    }

    /**
     * 生成校验码
     * @name: getSecdatacode
     * @param request
     * @param taskId 任务id
     * @param processInstanceId 流程实例id
     * @return: java.util.Map<java.lang.String,java.lang.String>
     * @date: 2022/10/19 11:51
     *
    */
    @RequestMapping(value = "/getSecdatacode", method = RequestMethod.GET)
    @ResponseBody
    public Map<String, String> getDocumentSecdatacode(HttpServletRequest request) {
        //处理平行越权问题
        Map<String, String> reMap = new HashMap<>();
        String taskId = request.getParameter("taskId");
        String processInstanceId = request.getParameter("processInstanceId");
        if (!DocumentValidateUtil.validateParamsString(taskId, processInstanceId)) {
            throw new ValidationException("非法参数");
        }
        //处理平台的平行越权
        Map<String, String> reCoedMap = new HashMap<>();
        if (StringUtils.isNotEmpty(processInstanceId)) {
            Map<String, String> coedMap = new HashMap<>();
            coedMap.put("id", taskId);
            coedMap.put("processInstanceId", processInstanceId);
            String encodeMap = DocumentSecUtils.documentListEncodeMap(coedMap);
            reCoedMap.put("approvedatacode", encodeMap);
        }
        return reCoedMap;


    }



}
